CRUD using CodeIgniter and EXTJS Grid – Part 1

July 10th, 2010   by  aditia rahman

In this post I want to share how to create simple CRUD (create, read, update, delete) using codeigniter ExtJS editor grid. In this first part, we will setup the database schema, codeigniter and extjs. I limited this first part, only setup fetching data from database and pagination grid in extjs grid.

1. Create Database Schema

The table that we will use is two tables with “has one” relationship, namely users table with foreign key country_id and countries table that store all the countries data, so when we want to know the country name from the users we have to get from the countries table, and here the sql for creating the table.

--
-- Table structure for table `countries`
--

CREATE TABLE IF NOT EXISTS `countries` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `country_name` varchar(150) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=102 ;

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fullname` varchar(150) NOT NULL,
  `email` varchar(100) NOT NULL,
  `country_id` int(11) NOT NULL DEFAULT '1',
  `occupation` varchar(150) NOT NULL,
  `birthdate` date NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=26 ;

2. Setup Codeigniter

Like we always do in previous tutorial, there are the files that we have to setup: config.php, database.php, autoload.php and route.php, all this files are inside the same folder in codeigniter namely “application/system/config”, and don’t forget to setup the extjs file.
config.php file

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

database.php file

$db['default']['hostname'] = "localhost";
$db['default']['username'] = "root";
$db['default']['password'] = "";
$db['default']['database'] = "ci_extjs_crud";
$db['default']['dbdriver'] = "mysql";

autoload.php file

$autoload['libraries'] = array('database');
$autoload['helper'] = array('url');

route.php file

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

we will create user class so set the default route to user and the extjs file looks on my project folder (inside codeigniter)

ci-ext-folder

I already remove only the used extjs file so, it much smaller than the fresh copy

3. Create The Controller

Create file image.php inside codeigniter controller folder and add this code below, this class only have 3 function. First function is to initialize the controller class, the index function only to render the view file and the ext_get_all function is to get the data from database that will displayed on the grid, you can see inside that function there are code to handle the pagination and the related table, the output from this function have to be in JSON format, so it will make easier to be displayed on Extjs grid.

<?php

class User extends Controller {

    public function  __construct()
    {
        parent::Controller();
    }

    public function index()
    {
        $this->load->view('user/index');
    }

    public function ext_get_all()
    {
        $start = isset($_REQUEST['start']) ? $_REQUEST['start'] : 0;
	$limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : 10;

        $this->db->select('users.*, countries.country_name');
        $this->db->from('users');
        $this->db->join('countries',
                'countries.id = users.country_id');

        $this->db->limit($limit, $start);

        $query = $this->db->get();
        $results = $this->db->count_all('users');
        $arr = array();
        foreach ($query->result() as $obj)
        {
            $arr[] = $obj;
        }
        echo '{success:true,results:'. $results .
                ',rows:'.json_encode($arr).'}';
    }
}

4. Create The View

Create file index.php inside folder “application/views/user/”, just include the extjs file on the header that linked to file that we already setup on the step 2, and add this code below in the javascript tag (whatever you like whether in the separate file or in the same file)

<script type="text/javascript">
var BASE_URL = '<?php echo base_url(); ?>' + 'index.php/';
var BASE_PATH = '<?php echo base_url(); ?>';
var BASE_ICONS = BASE_PATH + 'assets/icons/';
Ext.onReady(function() {
    var strUsers = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            fields: [
                'id', 'fullname', 'email', 'country_id',
                'country_name', 'occupation', 'birthdate'
            ],
            root: 'rows', totalProperty: 'results'
        }),
        proxy: new Ext.data.HttpProxy({
            url: BASE_URL + 'user/ext_get_all',
            method: 'POST'
        })
    });

    var tbUsers = new Ext.Toolbar({
        items:[{
            text: 'Add',
            icon: BASE_ICONS + 'user_add.png'
        }, '-', {
            text: 'Delete',
            icon: BASE_ICONS + 'user_delete.png'
        }]
    });

    var cbGrid = new Ext.grid.CheckboxSelectionModel();

    var gridUsers = new Ext.grid.GridPanel({
        frame: true, border: true, stripeRows: true, sm: cbGrid,
        store: strUsers, loadMask: true, title: 'Users List',
        style: 'margin:0 auto;', height: 330, width: 722,
        columns: [
            cbGrid, {
                header: "Fullname",
                dataIndex: 'fullname',
                width: 180
            }, {
                header: "Email",
                dataIndex: 'email',
                width: 180
            }, {
                header: "Country",
                dataIndex: 'country_name',
                width: 120
            }, {
                header: "Occupation",
                dataIndex: 'occupation',
                width: 120
            }, {
                header: "Birth",
                dataIndex: 'birthdate',
                width: 80,
                renderer : Ext.util.Format.dateRenderer('d/m/Y')
            }
        ],
        tbar: tbUsers,
        bbar: new Ext.PagingToolbar({
            pageSize: 10,
            store: strUsers,
            displayInfo: true
        })
    });

    gridUsers.render('divgrid');
    strUsers.load();
});
</script>

The first screenshot from this tutorial is something like this and you can download all the code below, i have included the sql schema and all the extjs file that needed in this post.

ExtJS CodeIgniter-CRUD_Part_1

Download Source

Posted in Codeigniter Extjs1 Comment
Tags:

One Comment Leave a Comment

  1. suresh.katiki says:

    This is excellent job. Thank you.

Leave a Comment