I’ve searched the web looking for an easy way to get a nice datagrid using CodeIgniter when I came across a JQuery plugin from datatables.net. This is a real simple solution and it provides a lot of features like

  • Variable length pagination
  • On-the-fly filtering
  • Multi-column sorting with data type detection
  • Smart handling of column widths
  • Display data from almost any data source
  • DOM, Javascript array, Ajax file and server-side processing (PHP, C#, Perl, Ruby, AIR, Gears etc)
  • Scrolling options for table viewport
  • Fully internationalisable
  • jQuery UI ThemeRoller support

Things you will need:

  1. CodeIgniter
  2. JQuery
  3. DataTables.net Plugin

Let’s start with the basics.

Folder Structure: To get this working you will need a few files.

  1. Controller (“my_class.php”) – loads the model, gets the data then loads the view
  2. Model (“my_data_model.php”) – Makes the DB call
  3. Template files – I use a basic template scheme to create sites with CodeIgniter. You can read more about it here.
  4. View (“datagrid.php”) – displays the datagrid
  5. JQuery and DataTables libraries and styles.

Database: I have one table called “my_data” that contains the following columns “Id”, “FirstName”, and “LastName”

First thing we need to create is the model. This is a standard implementation of a Model from CodeIgniter.

Next we need a controller to get this data and send it to the view. Again this is pretty standard CodeIgniter code.

  1. Load the model
  2. Get the data from the model
  3. Loop through that data to create and array
  4. Send that array to the view

The magic is in JQuery and the DataTables Plugin. Here is the header file for the template I use so you can see the references to those libraries:

Inside the view you use CodeIgniter’s Table library to generate a table from the data that was sent by the controller. Ensure you give your table an id like this:

Ensure you reference that id inside the JQuery call. Here is all of the code:

Some would argue not to create a CodeIgnitor instance within the view because it violates the MVC model but I do it here because I want to know exactly what the view is creating without opening the controller file/method. If  you do not want to create a CodeIgnitor instance just move lines 16-27 to the controller and send back the entire table instead of the array of data.

Here is the final result with some styles added: