flexigrid Implementation in codeigniter July 20, 2009
Posted by phpentertainer in Uncategorized.Tags: codeigniter, flexigrid, JS API
13 comments
flexigrid is a very useful and light weight js data grids used with codeigniter and developed on JQuery. Looking nice and very easy to implement with very feiw configuration.
One can download it from the following link: flexigrid
I have used this API in my some projects with simple bit of work. The required configuration and way to use it is as follows-
I assume that you already have some bases on CI before reading this, if you dont, read their excellent documentation from here
Setup:
After downloading and extracting the library, config file and helper, import the country.sql table to your database and create 2 controllers, 1 model and 1 view:
- Controller flexigrid.php – This controller can be named anything, its the controller that’s going to configure and generate the grid’s structure (javascript) and load the view
- Controller ajax.php – This is the controller thats going to handle the AJAX requests
- Model ajax_model.php – This is the model thats going to make all the database calls that the ajax controller needs
- View flexigrid.php – This is the view thats going to display it all
Before continuing make sure you have the CI URL helper and the CI Database Library in “autoload”. Also you need the $config['base_url'] in the config.php file correctly set, with ending slash. (eg. http://flexigridci/)
Flexigrid Controller:
As said before, in this controller we are going to setup the grid’s structure.
First of all, we must load the flexigrid helper:
function Flexigrid ()
{
parent::Controller();
$this->load->helper('flexigrid');
}
Next, we have to create an array with all the columns that you want the grid to have, based on your query, so we can build the column header.
For example, for the query “SELECT id,iso,name,printable_name,iso3,numcode FROM country” we have to build the following array (insert the code below in the index function of your controller):
$colModel['id'] = array('ID',40,TRUE,'center',2);
$colModel['iso'] = array('ISO',40,TRUE,'center',0);
$colModel['name'] = array('Name',180,TRUE,'left',1);
$colModel['printable_name'] = array('Printable Name',120,TRUE,'left',0);
$colModel['iso3'] = array('ISO3',130, TRUE,'left',0);
$colModel['numcode'] = array('Number Code',80, TRUE, 'right',1);
$colModel['actions'] = array('Actions',80, FALSE, 'right',0);
Now, to setup the other parameters like “width”, “height”, and every other parameter that’s available on FlexiGrid we have to create another array:
$gridParams = array(
'width' => 'auto',
'height' => 400,
'rp' => 15,
'rpOptions' => '[10,15,20,25,40]',
'pagestat' => 'Displaying: {from} to {to} of {total} items.',
'blockOpacity' => 0.5,
'title' => 'Hello',
'showTableToggleBtn' => true
);
Now that we have the column array built and the parameters set, if we want to add some buttons to the top of the grid, like “Delete”, “Select All”, etc we have to build another array (this is optional). In this example we will have: “Delete”, “Select All”, “DeSelect All”:
$buttons[] = array('Delete','delete','test');
$buttons[] = array('separator');
$buttons[] = array('Select All','add','test');
$buttons[] = array('DeSelect All','delete','test');
$buttons[] = array('separator');
Now that we have our column header, buttons and parameters set, lets build the grid’s javascript. To do this we call a helper function:
$grid_js = build_grid_js('flex1',site_url("/ajax"),$colModel,'id','asc',$gridParams,$buttons);
Finally, we setup a data array to send to the view.
$data['js_grid'] = $grid_js;
$this->load->view('flexigrid',$data); //Load view
Ajax Model:
This is the model thats going to make all the database calls that the ajax controller needs. In this model, we need to call a Flexigrid lib function to help build the query according to the grid’s request. This function adds the limit, order and search functionality of the grid.
To do that, we have to build the querys. We can use two methods, one with CI’s active record, the other one without. I advise the active record aproach, its more clean and less likely to fail.
WITH ACTIVE RECORD (recommended):
First, we build the query that’s going to return the contents of the grid and execute it:
//Select table name
$table_name = "country";
//Build contents query
$this->db->select('id,iso,name,printable_name,iso3,numcode')->from($table_name);
$this->CI->flexigrid->build_query();//Add search, order and limit
//Get contents
$return['records'] = $this->db->get();
Then we build and execute the COUNT query, that’s going to count the total results returned by the content query:
//Build count query
$this->db->select('count(id) as record_count')->from($table_name);
$this->CI->flexigrid->build_query(FALSE); //Add search, order and limit
$record_count = $this->db->get();
$row = $record_count->row();
//Get Record Count
$return['record_count'] = $row->record_count;
Ajax Controller:
Now we move on to the Ajax controller. This is the controller that holds the methods that are called when there’s an AJAX request.
Again, we must load some flexigrid componentes like the library and model: function Ajax ()
{
parent::Controller();
$this->load->model('ajax_model');
$this->load->library('flexigrid');
}
Next lets get the records from the database and turn them into JSON format to send to the grid.
There are two ways of doing this. The simpler and best way, envolves using the php JSON Extension that needs to be installed on PHP. If you use this method, you increase the performance and reduce the code:
//Get countries
$records = $this->ajax_model->get_countries();
/*
* Json build WITH json_encode.
*/
foreach ($records['records']->result() as $row)
{
$record_items[] = array($row->id,
$row->id,
$row->iso,
$row->name,
''.addslashes($row->printable_name).'',
$row->iso3,
$row->numcode,
'config->item('base_url').'public/images/close.png\'> '
);
}
//Print please
$this->output->set_header($this->config->item('json_header'));
$this->output->set_output($this->flexigrid->json_build
($records['record_count'],
$record_items));
If you do not have the JSON PHP Extension installed, you can use the following method:
//Get countries
$records = $this->ajax_model->get_countries();
//Init json build
if ($this->flexigrid->init_json_build($records['record_count']))
{
//Add records
foreach ($records['records']->result() as $row)
{
$record_item = array($row->id,
$row->id,
$row->iso,
$row->name,
''.addslashes($row->printable_name).'',
$row->iso3,
$row->numcode,
'config->item('base_url').'public/images/close.png\'> '
);
$this->flexigrid->json_add_item($record_item);
}
//Last item added, close up.
$this->flexigrid->json_add_item();
}
//Print please
$this->output->set_header($this->config->item('json_header'));
$this->output->set_output($this->flexigrid->json_build);
Flexigrid View:
Finally, we setup the view:

We print the $js_grid variable, passed by the flexigrid controller that contains the javascript code, and insert the table id “flex1″ where the grid is going to apear.
Conclusion:
May be enough to implement it to your projects. If face any problem let me know or just comment on this topic.
Thanks to all



