CRUD using CodeIgniter and EXTJS Grid Part 3

July 13th, 2010 by aditia rahman / 39 Comments  

     

This is the final post of the series CodeIgniter and Extjs CRUD, if you want to read the previous posts, here the first part and the second part of this post. Basically we already finish all the crud feature on the second part this only another common feature to add in the application, so we will add a quick search field on the grid, and what you need is the search grid plugin, I’m using the extjs example search field plugin from this extjs grid tutorial, you can download the complete code and find this file searchfield.js and put it your desire folder, in this post i put on the “assets/js/ext/plugins/” folder. Now all you have to do just include the js file in the view file and change the controller method.

This is what to be included in view “system/views/user/index.php”

<script type="text/javascript" src="<?php echo base_url(); ?>assets/js/ext/plugins/searchfield.js"; ?>"></script>

Create and add new search field plugin to the grid toolbar

// the new search field
var searchUsers = new Ext.app.SearchField({
    store: strUsers,
    params: {start: 0, limit: 10},
    width: 180,
    id: 'fieldUsersSearch'
});

// add to the toolbar grid
var tbUsers = new Ext.Toolbar({
    items:[{
        text: 'Add',
        icon: BASE_ICONS + 'user_add.png',
        handler: function() {
            var User = gridUsers.getStore().recordType;
            var u = new User({
                fullname: 'New Full Name',
                email: 'New Email',
                country: 'Water Seven',
                occupation: 'Occupation',
                birthdate: '1899-10-10'
            });
            gridUsers.stopEditing();
            strUsers.insert(0, u);
            gridUsers.startEditing(0, 0);
        }
    }, '-', {
        text: 'Save Selected',
        disabled: true,
        id: 'btnSave',
        icon: BASE_ICONS + 'save.gif',
        handler: updateUsers
    }, '-', {
        text: 'Delete',
        icon: BASE_ICONS + 'user_delete.png',
        handler: deleteUsers
    }, '->', searchUsers]
});

Alternatively you can use saki grid search plugin follow this link http://gridsearch.extjs.eu/

And a little modification in controller “system/controller/user.php”

When you add search grid and doing a search query, the search field will give $_POST['query'] to the server and all we have to do is check whether the $_POST['query'] is set or not, if is set then do some query LIKE, in codeigniter you can see on the active record class .

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

    if (isset($_POST['query']))
    {
        $this->db->like('users.fullname', $_POST['query']);
        $this->db->or_like('users.email', $_POST['query']);
        $this->db->or_like('users.occupation', $_POST['query']);
        $this->db->or_like('users.birthdate', $_POST['query']);
        $this->db->or_like('countries.country_name', $_POST['query']);
    }

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

    $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).'}';
}

you can download all the source code in this post and here the final screen thumbnail result from all the of the post

ci_extjs_crud_3_final

Download Source

        submit to reddit Delicious

39 Comments Leave a Comment Subscribe RSS

  • Eric Maynard says:

    Your examples are awesome learning tools! Perfect timing on CI and ExtJs for me.

    Have you had any experience with Sencha Touch yet?

    Keep up the good work.

    • I haven’t taste the sencha touch yet, cause mobile web development is still new to me and trying to add sencha touch to my learn schedule,
      thanks for the support

  • anhphuoc says:

    Thanks you big big!

  • young seok kim says:

    thanks a lot !
    here, korea.

    i am studing in extjs with DB.

    this source is that i am looking for.

    thanks again ~~ ^.^

  • Eric Maynard says:

    I am trying to implement the Search field in Part 3 and I have found that unless I change

    var searchUsers = new Ext.app.SearchField({

    to

    var searchUsers = new Ext.ux.form.SearchField({

    The Grid will not render and I get this error: “Uncaught TypeError: undefined is not a function”

    Once I make that change, the grid renders, but it won’t save any data. Any ideas what might cause this?

  • Eric Maynard says:

    LOL – No sweat. I figured something had to be different. Now I can use this as a good learning experience in debugging Extjs.

  • sapatu-butut says:

    just one question is on my head.. :D
    why the data is not show when I’m accessing the application from another computer… why why why why??
    many thanks…

  • Taguchi says:

    Aditia,

    Thanks for your helpful tutorial. I do have a question. How would one do an search box with autofiltering? For example, how can we build an search box whereby the grid gets auto-filtered as the end-user types in their search terms?

    Perhaps you can do a part 4 and show us how to add-in that feature.

    Keep up the great work. Love your blog!

    Taguchi

  • Brad says:

    Hello,

    Absolutely loving this tutorial, has really helped me wrap my head around extJS. One problem: When I sort the grid, it only sorts the 10 results that are currently showing, not all of the results. Any ideas on how this can be fixed?

    • so far that I knew the sort feature is using grid default feature and that how it works, if you want more advance sorting like sort all of the data maybe you have to add some custom code

  • Desarrollo says:

    Thanks for this Aditia, it really help me with search. I had some trouble with the date when I receive it on the controller, but as I don’t need date, I delete it.

    Juanca

  • vdthutech says:

    i cant not add birthday. format date wrong ?

    • sorry for late answer, I try to figure it out too….
      but so far I remember the extjs date format send in the format like “1899-11-27T00:00:00″ but when I try it again it became like this “Wed Nov 15 1899 00:00:00 GMT-0800 (Pacific Standard Time)”

      the fastest way to fix it change the update users function it became like this

      function updateUsers() {
      var sm = gridUsers.getSelectionModel();
      var sel = sm.getSelections();
      var data = ”;
      for (i = 0; i var dt = new Date(sel[i].get(‘birthdate’));
      data = data + sel[i].get(‘id’) + ‘;’
      + sel[i].get(‘fullname’)
      + ‘;’ + sel[i].get(‘email’)
      + ‘;’ + sel[i].get(‘country_id’)
      + ‘;’ + sel[i].get(‘occupation’)
      + ‘;’ + dt.format(‘Y-m-d’)
      + ‘||’;
      }
      Ext.Ajax.request({
      url: BASE_URL + ‘user/ext_update’,
      method: ‘POST’,
      params: { postdata: data }
      });
      strUsers.load();
      }

  • Joko says:

    Hi Aditia
    This is awesome tutorial.
    I’ve downloaded the source code, and copy it in my localhost. But there is NO ROWS (only blank grid) displayed when I ran it on Firefox. And It works on IE.
    Could you please advise, why it’s happened? Since, I am a newbie in CI and ExtJS.

    Thanks.
    Joko

  • Tim says:

    It would be good to have the config.php file setup so that it simply works anywhere without any editing being required.

    i.e.

    $config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == “on”) ? “https” : “http”);
    $config['base_url'] .= “://”.$_SERVER['HTTP_HOST'];
    $config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),”",$_SERVER['SCRIPT_NAME']);

    Thanks,
    Tim.

  • madeinara says:

    good tutorial, nice work .. according to what I was looking for and I hope I can find a better article on your website.

  • Anton says:

    Hello,

    thanks for the tutorial!

    Just a small nitpick – you have a bug there. Instead of:

    $results = $this->db->count_all(‘users’);

    you should take into account that with LIKE you probably are going to end up with fewer results than “count_all()”. Check “count_all_results()”, for example.

  • Tom says:

    Where are you defining the base params for the store? I keep getting the error this.store.baseParams is undefined in SearchField.js when I try to submit a search.

  • Anibal says:

    Hi,

    The country field is displayed as name when grid is loaded.
    When modifiying the country it’s set the country id in the field and not the country name!

    The store for the contry is like this:

    remoteJsonStoreCountries = new Ext.data.JsonStore({
    fields: recordFieldsStrCountries,
    proxy: new Ext.data.HttpProxy({url: StrCountriesURL2, method: ‘POST’ }),
    root: ‘records’,
    paramNames: { start: ‘x01′, limit: ‘x02′ },
    totalProperty: “totalCount”,
    id : “remoteJsonStoreCountries”,
    autoload: true});

  • Maniac says:

    Hi People,
    An excellent tutorial! helped me hone my extjs skills and codeigniter, perfection combination. can’t wait to explore this tutorial further.

    p.s a little creativity won’t hurt for those having issues with the tutorial :)

  • bagas says:

    great tuts!

  • top1 says:

    assalamu’alaikum mas adit.,
    saya mau tanya.,
    ci n extjs yg digunakan versi berapa ya?
    lalu., gmn dengan lisensi extjs-nya ? apa bebas digunakan

    regards.,

    top1

    • sorry sekarang saya ga explore extjs, tapi coba add this code on country combobox, its extjs 3

      listeners: {
      ‘change’: function() {
      gridUsers.getSelectionModel().getSelected().data.country_id = this.value;
      console.log(this.value, gridUsers.getSelectionModel().getSelected().data.country_id);
      }
      }

  • Yazid Erman says:

    Hi Guys,

    Thank you Rahman, i have some extra fixes also:

    The function updateUsers() have two problems, it sends the list of to be changed raws ended with an extra “||”, and this leads to extra request to the database with null values, the other problem is that is sends always ’1′ as the country id whatever it was. these two problems were fixed in the following code:

    function updateUsers() {
    var sm = gridUsers.getSelectionModel();
    var sel = sm.getSelections();
    var data = ”;
    for (i = 0; i<sel.length; i++) {
    var dt = new Date(sel[i].get('birthdate'));
    data = data + sel[i].get('id') + ';'
    + sel[i].get('fullname')
    + ';' + sel[i].get('email')
    + ';' + sel[i].get('country_name')
    + ';' + sel[i].get('occupation')
    + ';' + dt.format('Y-m-d');

    if (i < sel.length-1){data += '||';}

    }
    console.log(data);
    Ext.Ajax.request({
    url: BASE_URL + 'user/ext_update',
    method: 'POST',
    params: { postdata: data }
    });
    strUsers.load();
    }

Leave a Comment