[OUTDATED] PHP Codeigniter full featrued JQuery datatables [Part 1]

Posted on

datatables_final3

Demo Source

Introduction

This tutorial will get your through how to create cool full featured datatables for your daily use in any Codeigniter projects specially CMS and how to add controls (i.e. buttons, anchors)

Assumptions:

  • You are familiar with Codeigniter
  • You have a webserver up and running  (XAMP,LAMP or WAMP)

Step 1 : Setting up for the demo:

Create database with the below script

CREATE TABLE `subscriber` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first` varchar(100) DEFAULT NULL,
`last` varchar(100) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1;
insert into `subscriber`(`id`,`first`,`last`,`email`,`date_created`) values (23,'Ahmedd','samy','ahmed.samy.cs@gmail.com','2013-03-11 23:11:40');
insert into `subscriber`(`id`,`first`,`last`,`email`,`date_created`) values (24,'John','Carter','test@test.com','2013-03-11 23:19:05');
insert into `subscriber`(`id`,`first`,`last`,`email`,`date_created`) values (25,'Lina','Khaled','lina@hotmail.com','2013-03-17 20:54:48');

-Download and extract Codeigniter in your root folder

Change base_url  in your application/config/config.php file to

$config['base_url'] = 'http://localhost/tutorial_datatables;

Make sure you set database configuration in your application/config/database.php

-Download ignited datatables library from https://github.com/IgnitedDatatables/Ignited-Datatables

-Copy Datatables.php in application/libraries

-Download Datatables JS plugin from http://www.datatables.net/download/

- Create assets folder with the below structure

folders

Copy jquery.dataTables.min.js   from  DataTables-1.9.4\media\js  to assets\js

-Create a CSS file called style.css in assets/css

body{font-family:Arial,Helvetica,sans-serif;background-color:#F0F0F0;font-size:12px;}
h1{color:#072936;}
.wrapper{width:730px;margin:0 auto;}
footer{border-top:1px solid #CCC;float:right;font-size:12px;width:81%;margin:40px 0 0;padding:10px;}
#big_table_wrapper{background-color:#fff;}
#big_table_wrapper .dataTables_length{float:left;}
#big_table_wrapper .dataTables_filter{float:right;}
#big_Table_wrapper .ui-toolbar{padding:5px;}
#big_table{width:730px;text-align: center;}
.dataTables_paginate .ui-button{margin-right:-.1em!important;}
.paging_full_numbers .ui-button{color:#333!important;cursor:pointer;margin:0;padding:2px 6px;}
.dataTables_info{float:left;width:50%;padding-top:3px;}
.dataTables_paginate{float:right;text-align:right;width:auto;}
.paging_full_numbers{width:350px!important;}
#big_table_processing > img{padding-left:20px;}</code>

Step 2 : Create the MVC:

-Change the default controller in application/config/routes.php


$route['default_controller'] = "subscriber";

-Create the controller subscriber in application/controller

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Subscriber extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->library('Datatables');
        $this->load->library('table');
        $this->load->database();
    }

    function index()
    {

        //set table id in table open tag
        $tmpl = array('table_open' => '<table id="big_table" border="1" cellpadding="2" cellspacing="1" class="mytable">');
        $this->table->set_template($tmpl);

        $this->table->set_heading('First Name', 'Last Name', 'Email');

        $this->load->view('subscriber_view');
    }

    //function to handle callbacks
    function datatable()
    {
        $this->datatables->select('id,first,last,email')
            ->unset_column('id')
            ->from('subscriber');

        echo $this->datatables->generate();
    }
}

It’s not mandatory to assign a template to the table but it’s preferable to select the table by its id

$this->table->set_template($tmpl);

is the callback function for JQuery datatables plugin and this contain what the table should have at the first state

datatable()

we have our database code should be placed separately in a model file of course but for sake of simplicity we will just put in the controller function

-Create the view subscriber_view in application/views

<h1>Subscriber management</h1>
<?php echo $this->table->generate(); ?>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        var oTable = $('#big_table').dataTable({
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": '<?php echo base_url(); ?>index.php/subscriber/datatable',
            "bJQueryUI": true,
            "sPaginationType": "full_numbers",
            "iDisplayStart ": 20,
            "oLanguage": {
                "sProcessing": "<img src='<?php echo base_url(); ?>assets/images/ajax-loader_dark.gif'>"
            },
            "fnInitComplete": function () {
                //oTable.fnAdjustColumnSizing();
            },
            'fnServerData': function (sSource, aoData, fnCallback) {
                $.ajax
                ({
                    'dataType': 'json',
                    'type': 'POST',
                    'url': sSource,
                    'data': aoData,
                    'success': fnCallback
                });
            }
        });
    });
</script>

We intiate the datatable JQuery pluging by calling

$('#big_table').dataTable 

where “big_table” is the table id we set in table template

"sAjaxSource": '<?php echo base_url(); ?>index.php/subscriber/datatable'

is where you specify the path of function that handle the callbacks
in every change like pagination, search, sorting…etc (Where the actual Ajax magic happens)

<?php echo $this->table->generate(); ?>

for printing the table only for settings the headers and for the first time and then callback function will take over

Step 3 : Styling:

Styling such table may take a lot of time but don’t panic there’s still more magic introduced by JQuery UI team, is the ThemeRoller

DataTables has full support for ThemeRoller

Conclusion:

  • Integration between JQuery datatables and Codeigniter thought ignited datatables library
  • Customization for the style through the cool ThemeRoller

In next part of this tutorial we walk you through a real world daily example , how we can integrate controls inside the Ignited Datatables to use our simple CRUD functionality in less time

Check PHP Codeigniter full featrued JQuery datatables [Part 2]

Code Igniter: http://ellislab.com/codeigniter
DataTables: http://datatables.net/
IgnitedTables: https://github.com/IgnitedDatatables/Ignited-Datatables/

Tags: , , ,


Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *