I am attempting to add some styling to a table in Code Igniter, I realize CI has a built in table library to help achieve this. I'm unsure how to implement this in my specific implementation however. I'm looking to incorporate these inbuilt functions:
$this->load->library('table');
$this->table->set_heading(array('Name', 'Color', 'Size'));
How can I add those functions in my specific implementation?
I have the following controller:
public function ecomma(){
$this->load->model('report_model');
$data ['query'] = $this->report_model->generate_ecomm_data_report();
$this->load->view('report_view', $data);
}
My view:
<table>
<tbody>
<?php foreach($query as $row): ?>
<tr>
<td><?php echo $row->no_skus; ?></td>
<td><?php echo $row->brand; ?></td>
<td><?php echo $row->unique_models; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Using the Table library is quite easy. This example requires that generate_ecomm_data_report()returns the results of a query. For example:
return $this->db->query('YOUR QUERY HERE');
Controller:
public function ecomma(){
$this->load->library('table');
$this->load->model('report_model');
$query = $this->report_model->generate_ecomm_data_report();
One advantage to the Table library is that styling is quite easy using the template scheme of the class. For instance to add a CSS class to the header and to rows.
controller continues:
$my_styles = array(
"thead_open" => "<thead class='my_style'>",
"row_start' => '<tr class='my-row-style'>");
$this->table->set_template($my_styles);
$this->table->set_heading(array('Name', 'Color', 'Size'));
$data[table] = $this->table->generate($query);
$this->load->view('report_view', $data);
}
View:
<?php echo isset($table) ? $table : "No Data"; ?>
The result will be a table structure like the one you create in the foreach loop - only this one has style.
Related
I have a section in my .html page where I want to run some PHP code, which reads data from a database and 'echoes' the table filled up with that information. I kinda did it object-oriented so I'm trying to keep that along the project.
I have this exact function or method in the Class (Class Servicio):
public static function listaServicios(){
$servicios = array();
$query = "";
$db = Database::getInstance();
$query = "SELECT descripcion, precio FROM servicio";
$resultado = $db->conn()->query($query);
foreach($resultado as $item){
$servicio = new Servicio();
$servicio->setDescripcion($item['descripcion']);
$servicio->setPrecio($item['precio']);
array_push($servicios,$servicio);
}
return $servicios;
}
As you can see, the function just returns an array filled up with as many objects as rows there is in the table. The PHP page would call this method, and then print the table with the selected data inside (there is no problem with this).
The thing is how can I print it in the specific section (div with id='datos') previously mentioned, which simply is:
<section class="principal">
<div id="datos">
</div>
</section>
I kinda of have an idea but I really don't know to implement it. Maybe using a document.ready function in jQuery calling the PHP code? I would really like to use this language even if it is a very tiny function in order to learn.
You can use jquery's load function to load content via a remote file into the div. But you will need to update your listaServicios to return html instead of the array.
jquery:
$(document).ready(function(){
$('#datos').load('phpfile.php');
});
phpfile.php
<?php
$serv = new Servicio();
echo $serv->listaServicios();
?>
Correct answer to your question depends on the interface of your future application you want to reach.
If you want some kind of SPA, then you should make AJAX-requests using JavaScript (jQuery or something else) and create a separate controller to response with data.
But I think in your particular case you can do everything on server side.
First of all you should add new method to your class, name f.e. render:
public static function render(){
$services = static::listaServicios();
include 'path/to/your/template.php';
}
Then inside your template.php write next:
<section class="principal">
<div id="datos">
<?php
foreach($services as $service) {
// echo your $service here as you wish
}
?>
</div>
</section>
So after calling render() PHP will render that part of template.
To access the properties of Servicio is better you construct your table in php:
<?php $servicios = Servicio::listaServicios(); ?>
<section class="principal">
<div id="datos">
<table style="width:100%">
<tr>
<th>Descripcion</th>
<th>Precio</th>
</tr>
<?php foreach ($servicios as $servicio): ?>
<tr>
<td><?= $servicio->getDescripcion() ?></td>
<td><?= $servicio->getPrecio() ?></td>
</tr>
<?php endforeach; ?>
</table>
</div>
</section>
Im using a custom MVC in PHP
I have two tables.
Controles and professors
professors table contains an id of course --> id_professor
controles table contains a field called --> id_professors in which I store a list of profs ids this way ==> 1;2;5;9
In my datatable Im retrieving a list of controles from controles table
for the Model, Im using this class
public function fetchControlesListe(){
stmt = $this->db->prepare("SELECT * FROM controles ");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
return $stmt->fetchAll();
}
Controller
liste_controles.php
class Liste_Controles extends Controller {
function __construct(){
parent::__construct();
}
$this->view->fetchCtrlListe= $this->model->fetchControlesListe();
$this->view->render('liste_controles/index');
}
VIEW
<table>
<thead>
<tr>
<th>N°</th>
<th>Module</th>
<th>Salle</th>
<th>Surveillants</th>
</tr>
</thead>
<tbody>
<?php foreach($this->fetchCtrlListe AS $key=>$value): ?>
<tr>
<td><?php echo $controle['id_controle']; ?></td>
<td><?php echo $controle['intitule_module']; ?></td> <
<td><?php echo $controle['intitule_salle'];?></td>
<td>
<?php foreach($this->prof as $profs): ?>
HERE, I would like to retrieve the list of profs from professors
table and the field id_profs in professors table stores an
array, as i said before, containing a list of ids (Ex: 1;2;3;4;5)
I would like to loop through that array and retrieve the name of
professor from professors table if the id_professor Exists in that array
. I know I have to create another METHOD but The PROBLEM is i don't know how to pass parameters in the method and call it from the controller to pass it to the view . and the param would be $controle['id_professor']
<?php endforeach; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
The result would be like this:
EDIT:
I know that is not a good idea to store lots of ids as an array, but
my question I just want to know how to do a foreach loop inside
another foreach loop using another method with a paramater that will
be passed from the first loop
There isn't one solution but what you can do is, because you know that id_professors is a string composed of ids separated by commas, you can retrieve an array of identifiers this way :
$ids = explode(",", $profs[id_professors']);
and then
<?php foreach($this->prof as $profs): ?>
<?php $ids = explode(",", $profs['id_professors']); ?>
<?php foreach($ids as $id): ?>
//DO STUFF with $id
<?php endforeach; ?>
<?php endforeach; ?>
Notice that the entire thing is not very beautiful because of opening/closing php tags constantly but I hope you'll make a wonderful templates system for your MVC framework :)
From there, it would not be that nice to access the database directly from the view so a better (not perfect) solution would be to provide the view an array made of professors like this one :
$this->view->profs_list = array(
1 => "Prof 1",
2 => "Prof 2",
//etc.
);
with the key of the array being the profs' identifier.
Then you can retrieve their name through the loop :
<?php foreach($this->prof as $profs): ?>
<?php $ids = explode(",", $profs['id_professors']); ?>
<?php foreach($ids as $id): ?>
<span><?php echo $this->profs_list[$id]; ?></span><br />
<?php endforeach; ?>
<?php endforeach; ?>
I am coming from Asp.net world, where everything is so modular that it creates headaches and nausea sometimes and you forget what you were actually doing.
Here in PHP I was trying to study how to display tabular data, and the solution was very simple but that looked very hasty, because if I write lots of code then it will become haywire.
So my question is what standard should I follow to work with repeating data, if there is any? Please guide me to some quality material to study because I tried but did not find anything. I have studied this link.
[Edit]
The way asp.net render tabular data is by using GridView. here you just create an instance of the GridView class and send it the data retrieved from the database and remain job is done behind the scene without messing the C# or VB code with html or writing the same logic again and again. I mean it is nice example of code resuability and I want to utilize something similar here in php to write the repeating code once and then inherit it if I want it somewhere else.
I myself have migrated from ASP.NET to php and one word of advice is forget what ever you learnt in ASP.net as ASP.net abstracts a lot of thing in web development to a point you forget that you are working with basic html/jscript and http. but again, this is just a personal opinion.
Ragarding your question on how to display a table and populate it with data. Have a look at this example. Here
<?php
$people = array(
array('Tom', '16'),
array('John', '21'),
array('Kate', '19'),
array('Luke', '25')
)
?>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<td>Name</td><td>Age</td>
</tr>
<?php foreach($people as $person){ ?>
<tr>
<td><?php echo $person[0]; ?></td>
<td><?php echo $person[1]; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
I create a 2d array contain data about People and their age. Due to simplicity sake, im using a hard coded array and not retrieving data from a database.
I then use a while loop to loop through the data in the array and for each tuple, I add a <tr> in the table. This is something like a repeater in ASP.NET
DEMO
Just noticed you want a modularized version. Here is an example:
index.php
<?php
include('inc.datasource.php');
$people = DataSource::getUsers();
?>
<html>
<head>
<title></title>
</head>
<body>
<table>
<tr>
<td>Name</td><td>Age</td>
</tr>
<!-- Render rows with data -->
<?php foreach($people as $person){ ?>
<tr>
<td><?php echo $person[0]; ?></td>
<td><?php echo $person[1]; ?></td>
</tr>
<?php } ?>
<!-- End render rows with data -->
</table>
</body>
</html>
inc.database.php
<?php
class DataSource{
public static function getUsers(){
//Connect to database
//Retrieve user data
//Return user data
//Simulating the above steps for simplicity sake
$people = array(
array('Tom', '16'),
array('John', '21'),
array('Kate', '19'),
array('Luke', '25')
);
return $people;
}
}
?>
If you want to completly seperate your php from your html. I suggest you use one of the php mvc frameworks. I personally like using Laravel and CodeIgniter
I have one java script definition in view(.phtml) file. This java script has dynamic parameters like controller name and action name. To avoid duplicate code i want to put this code in helper file.
Now is it possible that i can use pure html and javascript code in helper file? If yes then how can i call that helper in my view file?
Or Is there any other best way to do this?
Thank you...
A view helper would not be the solution in this instance. More likely you will want to use a partial (which is a view helper). A view helper is something normally used to return a piece of data to the view. A partial() or partialLoop() is used to display common html in the view (pieces of html that can be reused in multiple views).
Here is an example of a simple view helper, notice it returns a result:
<?php
class Zend_View_Helper_FormatDate extends Zend_View_Helper_Abstract
{
public function FormatDate($date) {
if ($date != NULL) {
$formatedDate = new DateTime($date);
$format = $formatedDate->format('M d, Y');
return $format;
} else {
return '';
}
}
}
//This is called in the view like any other function
<?php echo $this->FormatDate($date) ?>
Now a partial will contain Html (I'm petty sure JS will work as well)
Here is a partial that uses view helpers
fieldset><legend>Dates and Qualifications</legend>
<table>
<tr>
<td>Birth Date: </td><td><?php echo $this->escape($this->FormatDate($this->bdate)) ?></td>
</tr>
<tr>
<td>Seniority Date: </td><td><?php echo $this->escape($this->FormatDate($this->sendate)) ?></td>
</tr>
</table>
<table>
<tr>
<td>I'm a Lead:</td><td><?php echo $this->escape(ucfirst($this->ToBool($this->lead))) ?></td>
</tr>
<tr>
<td>Lead Date:</td><td><?php echo $this->escape($this->FormatDate($this->ldate)) ?></td>
</tr>
<tr>
<td>I'm an Inspector:</td><td><?php echo $this->escape(ucfirst($this->toBool($this->inspector))) ?></td>
</tr>
<tr>
<td>Admin Login:</td><td><?php echo $this->escape(ucfirst($this->toBool($this->admin))) ?></td>
</tr>
</table>
</fieldset>
call this partial in your view script, the first argument is the path of the partial
the second argument is the data used in the partial
<?php echo $this->partial('_dates.phtml', $this->memberData) ?>
the data is sent from the controller action as usual $this->view->memberData = $memberData This is common usage but not the only way to get data to the partial.
in this example the partial is at the default location /application/views/scripts
Hope this helps
I am using a propel form to allow a user to create an account, the form has two parts; the entering and then the preview.
On my preview page I declare the values of the form as usual and these are provided by the previous form
public function configure() {
//Preview page no fields are displayed anyway xD
$this->useFields(array('email', 'user_gender_id', 'search_gender_id', 'content', 'age', 'location'));
But instead of outputting the fields I am trying to render the values on the page:
<?php echo $form->renderHiddenFields(); ?>
<?php foreach($form as $field): ?>
<?php if(!$field->isHidden()): ?>
<tr>
<th><?php echo $field->renderLabel() ?></th>
<td><?php echo $field->getValue(); ?></td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
<?php else: ?>
<?php echo $form; ?>
<?php endif; ?>
Unfortunately for my sfWidgetFormPropelChoice / sfWidgetFormChoice fields it just outputs the chosen ID rather than a string representation of it.
Is there a proper way in Symfony to output the text representation of a widget's value? Or do I have to hack something together? (any ideas?)
Many thanks,
Pez,
Try:
$obj = $form->getObject();
to have the values of your object. Then:
echo $obj[$field->getName()];
this can work in most cases. But, if it won't, you'll have to write all the preview fields by hand and display them using the $obj above.
I got around this problem by doing the following:
<td><?php if(method_exists($field->getWidget(), "getChoices")) {
$choices = $field->getWidget()->getChoices();
echo $choices[$field->getValue()];
} else
echo $field->getValue();
?></td>
I hope this is of use to someone as it has been driving me crazy!