19 January 2011 ~ 5 Comments

ExtJs Grid refresh

This post is about how to refresh ExtJs Grid. Refreshing the ExtJs Grid is achieved by a reload of the ExtJs store attached to the ExtJs Grid. If you are not familiar with how ExtJs grids work, you should read the following post: ExtJs Grid.The example used is the same as in the ExtJs Grid post.

This is the basic example code used:

var data = [
            ['Østfold',271662,2252,1960,292,7465,2148,5168,1053,2297,2589,274251],
            ['Akershus',536499,4979,2758,2221,22494,6354,17572,3181,4922,7143,543642],
            ['Oslo',586860,7795,3202,4593,34004,13434,28534,7453,5470,10063,596923],
            ['Hedmark',190709,1362,1625,-263,4892,1413,3873,488,1019,756,191465],
            ['Oppland',185216,1410,1489,-79,4895,1493,4110,488,785,706,185922],
            ['Buskerud',257673,2194,1703,491,8238,2791,6185,941,2053,2544,260217],
            ['Vestfold',231286,1846,1478,368,6719,2121,5175,951,1544,1912,233198],
            ['Telemark',168231,1355,1228,127,3773,1252,3037,422,736,863,169094],
            ['Aust-Agder',108499,1046,716,330,3267,965,2288,283,979,1309,109808],
            ['Vest-Agder',170377,1687,1046,641,4658,1586,3655,517,1003,1644,172021],
            ['Rogaland',427947,4954,2246,2708,11133,6235,7216,2152,3917,6625,434572],
            ['Hordaland',477175,4847,2800,2047,11732,5232,7880,1506,3852,5899,483074],
            ['Sogn og Fjordane',107080,937,698,239,2626,1196,2310,282,316,555,107635],
            ['Møre og Romsdal',251262,2164,1659,505,6001,2907,4434,820,1567,2072,253334],
            ['Sør-Trøndelag',290547,2997,1805,1192,9174,3013,7407,1542,1767,2959,293506],
            ['Nord-Trøndelag',131555,1126,972,154,3071,852,2938,459,133,287,131842],
            ['Nordland',236271,1934,1705,229,5262,1924,4709,528,553,782,237053],
            ['Troms Romsa',156494,1457,930,527,4627,1683,4260,642,367,894,157388],
            ['Finnmark Finnmárku',72856,652,514,138,2433,908,2225,311,208,346,73202]
        ];
        var store = new Ext.data.ArrayStore({
            fields: [
                { name: "state",                   type: "string"    },
                { name: "population_01_01_10",     type: "int"       },
                { name: "born",                    type: "int"       },
                { name: "dead",                    type: "int"       },
                { name: "born_sub_dead",           type: "int"       },
                { name: "moving_in_total",         type: "int"       },
                { name: "moving_in_foreigners",    type: "int"       },
                { name: "moving_out_total",        type: "int"       },
                { name: "moving_out_foreigners",   type: "int"       },
                { name: "neto_movin_in",           type: "int"       },
                { name: "population_growth",       type: "int"       },
                { name: "population_01_10_10",     type: "int"       }
            ],
            data: data
        });
        var grid = new Ext.grid.GridPanel({
            renderTo:Ext.getBody(),
            store: store,
            autoHeight: true,
            cm: new Ext.grid.ColumnModel({
                columns:[
                     { header: "State",                 dataIndex: "state" },
                     { header: "Population 01.01.10",   dataIndex: "population_01_01_10", sortable: true},
                     { header: "Population 01.10.10",   dataIndex: "population_01_10_10", sortable: true},
                     { header: "New born",              dataIndex: "born",                sortable: true, hidden: true}
                ]
            })
        });

The above should produce the following output:

Grid refresh – the concept

An ExtJs GridPanel is connected to an ExtJs store, in this example we use a simple ExtJs ArrayStore. The ExtJs Grid listens to events in the Ext Store, so each time the Ext ArrayStore is changed – the Ext grid automagicly reloads. Let’s see what happens if we add a button to our Ext grid that removes the last record in the Ext Store:

        var button = new Ext.Button({
        	text:"Remove last record", 
        	handler: function() {
        	   var store = Ext.getCmp("grid").getStore();
        	   store.removeAt(store.getCount()-1);
            },
            renderTo: Ext.getBody()
        });
        var grid = new Ext.grid.GridPanel({
            id: "grid",
            renderTo:Ext.getBody(),
            store: store,
            autoHeight: true,
            cm: new Ext.grid.ColumnModel({
                columns:[
                     { header: "State",                 dataIndex: "state" },
                     { header: "Population 01.01.10",   dataIndex: "population_01_01_10", sortable: true},
                     { header: "Population 01.10.10",   dataIndex: "population_01_10_10", sortable: true},
                     { header: "New born",              dataIndex: "born",                sortable: true, hidden: true}
                ]
            })
        });

Make notice of a slight change in the ExtJs GridPanel code above. I have added an id to the config options. This i so that we in a simple way can reach the Ext GridPanel when we are out of scope, by using Ext.getCmp(). The above will give us the following Ext.Button followed by an ExtJs GridPanel:

As you can see, by clicking the “Remove lat record” button, the Ext Gridpanel is reloaded for each click. Let’s walk through the code to see what actually happens when you click the ExtButton:

        var button = new Ext.Button({
        	text:"Remove last record", 
        	handler: function() {
        	   var store = Ext.getCmp("grid").getStore();
        	   store.removeAt(store.getCount()-1);
            },
            renderTo: Ext.getBody()
        });

If you are not familiar with buttons, try google ExtJs button. The point is very simple:

On line 2 you add the actual text label to the Ext Button.
Line 3 attaches a handler for the click event. Inside the handler, we first get the Ext grid by using Ext.getCmp(“grid”), where “grid” is the configured id of the Ext grid. Then, we use the ExtJs store method removeAt() to remove a record from the Ext ArrayStore. Simple magic.

ExtJs Grid Panel refresh conclusion / summary

Reloading an ExtJs GridPanel has nothing to do with the Ext Grid itself. You are, as when filtering an extjs gridpanel, changing the records in the Ext Data Store attached to the Ext Grid.

You can see a working example here: http://aboutfrontend.com/examples/extjs-grid-refresh/

Feel free to ask any questions.

Further reading

Professional JavaScript Frameworks: Prototype,YUI, ExtJS, Dojo and MooTools
Beginning PHP RIA Using Extjs
Zend Studio for Eclipse Developer's Guide

5 Responses to “ExtJs Grid refresh”

  1. Deckard Cain 22 April 2011 at 11:03 Permalink

    I have been looking for this. Although the post is recent, I think they changed something in the extjs 4 beta2+

    Ext.getCmp(“grid”).getStore();
    getStore is undefined =/

  2. Deckard Cain 22 April 2011 at 11:09 Permalink

    Oh I got it!

    var grid = Ext.getCmp(‘grid’).getView();
    grid.getStore().load();

    😉

  3. Nils-Fredrik 22 April 2011 at 20:48 Permalink

    @Decakard, thanks!

    I will update the examples here, and check my other posts against ExtJs 4 too.

  4. Robert 2 May 2012 at 18:56 Permalink

    I, i got a litle problem with a grid… u see, i got this .js class
    /**
    * @author RCGA
    */
    // example of custom renderer function
    function change(val){
    if(val < 80){
    return '’ + val + ”;
    }else if(val > 80){
    return ” + val + ”;
    }
    return val;
    }
    // create the data store
    var store = new Ext.data.Store({
    storeId: ‘storemostrar’,
    //baseParams: {lightWeight:true,ext: ‘js’},
    sortInfo: {field:’grid_FECHA’, direction:’ASC’},
    autoLoad: {params:{start:0, limit:10}},
    proxy: new Ext.data.HttpProxy({
    url: ‘Controlador/_consultaVolante.php’
    }),
    autoLoad: false,
    //url: ‘Controlador/_consultaVolante.php’,
    reader: new Ext.data.JsonReader({
    root: ‘estructura’,
    totalProperty: ‘count’
    }, [‘grid_V_D’, ‘grid_FECHA’, ‘grid_NOMBRE_PACIENTE’,’grid_DIRECCION_PACIENTE’,’grid_EDAD_PACIENTE’,’grid_SEXO_PACIENTE’, ‘grid_HORA_ACTIVACION’,’grid_HORA_SALIDA’,’grid_ACTIVA’,’grid_REG_PROFESIONAL’,’grid_DIAGNOSTICO’,’grid_ORIGEN’,’grid_DESTINO’,’grid_ID_CLASIFICACION’,’grid_MOVIL’])/*,
    remoteSort: true,*/
    });

    //store.load({params:{start:0, limit:10}});

    CconsultaVolante = function(){
    CconsultaVolante.superclass.constructor.call(this, {

    region : “center”,
    id : ‘consultaVolante’,
    autoScroll : true,
    frame : true,
    items: [{
    xtype : ‘form’,
    buttonAlign : ‘left’,
    closable : true,
    autoScroll : true,
    url : ‘Controlador/_consultaVolante.php’,
    id : ‘frm_consultaVolante’,
    //width : 490,
    bodyStyle : ‘padding: 5px 5px 5px 10px’,
    frame : true,
    labelAlign : ‘top’,
    style : ‘margin: 3px 3px 3px 3px;’,
    title : ‘Registrar en Hoja de Cargo’,
    items: [{
    xtype : ‘textfield’,
    fieldLabel : ‘V/D’,
    id : ‘consult_V_D’,
    tabIndex : 1,
    allowBlank : false/*,
    regex : /^[1-9][0-9]{0,1}\/{1,1}[0-9]{1,}/,
    regexText : ‘El valor es incorrecto, pruebe entrar un valor con el formato 1/2.’*/
    },
    {
    xtype : ‘grid’,
    id : ‘id_grid’,
    frame : true,
    store : store,
    /*renderer: change,*/
    columns: [
    {id:’grid_V_D’,header: “V/D”, width: 20, dataIndex: ‘grid_V_D’},
    {header: “Fecha”, width: 70, sortable: true, renderer: Ext.util.Format.dateRenderer(‘d/m/Y’), dataIndex: ‘grid_FECHA’},
    {header: “Nombre del paciente”, width: 140, dataIndex: ‘grid_NOMBRE_PACIENTE’},
    {header: “Dirección del paciente”, width: 140, dataIndex: ‘grid_DIRECCION_PACIENTE’},
    {header: “Edad”, width: 40, sortable: true, renderer: change, dataIndex: ‘grid_EDAD_PACIENTE’},
    {header: “Sexo”, width: 40, dataIndex: ‘grid_SEXO_PACIENTE’},
    {header: “Hora activación”, width: 75, dataIndex: ‘grid_HORA_ACTIVACION’},
    {header: “Hora salida”, width: 75, dataIndex: ‘grid_HORA_SALIDA’},
    {header: “Activa”, width: 75, dataIndex: ‘grid_ACTIVA’},
    {header: “Reg. Profesional”, width: 75, dataIndex: ‘grid_REG_PROFESIONAL’},
    {header: “Diagnóstico”, width: 75, dataIndex: ‘grid_DIAGNOSTICO’},
    {header: “Origen”, width: 75, dataIndex: ‘grid_ORIGEN’},
    {header: “Destino”, width: 75, dataIndex: ‘grid_DESTINO’},
    {header: “Clasificación”, width: 75, dataIndex: ‘grid_ID_CLASIFICACION’},
    {header: “Móvil”, width: 75, dataIndex: ‘grid_MOVIL’}
    ],
    stripeRows: true,
    autoExpandColumn: ‘grid_V_D’,
    plugins: new Ext.ux.PanelResizer({
    minHeight: 150
    }),
    viewConfig: {
    enableRowBody:true
    },
    bbar: new Ext.PagingToolbar({
    pageSize: 10,
    store: store,
    displayInfo: true,
    displayMsg: ‘Mostrando registros {0} – {1} de {2}’,
    emptyMsg: “No hay registros para mostrar”
    })
    }
    ],
    buttons: [
    {
    text:’Consultar’,
    handler : function(){
    if (Ext.getCmp(‘frm_consultaVolante’).form.isValid()) {
    Ext.getCmp(‘frm_consultaVolante’).form.submit({
    waitMsg: ‘Consultando…’,
    waitTitle: ‘Espere por favor’,
    success: function(resp){
    Ext.getCmp(‘frm_consultaVolante’).form.reset();
    Ext.MessageBox.alert(‘Status’, ‘Changes saved successfully.’);
    this.store.load({params:{start:0, limit:10}});
    Ext.getCmp(‘storemostrar’).doLayout();
    },
    failure: function(resp){
    Ext.Msg.show({
    title: ‘Error’,
    msg: ‘No se pudo registrar en la base de datos.’,
    buttons: Ext.Msg.OK,
    icon: Ext.MessageBox.ERROR
    });
    }

    });
    }
    else {
    Ext.Msg.show({
    title: ‘Error’,
    msg: ‘Los datos son incorrectos’,
    buttons: Ext.Msg.OK,
    icon: Ext.MessageBox.ERROR
    });
    }
    }
    },{
    text: ‘Cancelar’,
    handler: function(){
    var hojaCargo= Ext.getCmp(‘consultaVolante’);
    hojaCargo.destroy();
    Ext.getCmp(‘mainPanelExt’).doLayout();
    }
    },
    {
    text:’Resetear’,
    id : ‘resetear’,
    handler: function(){
    Ext.getCmp(‘frm_consultaVolante’).form.reset();
    }
    }
    ]
    }]

    });
    }
    Ext.extend(CconsultaVolante, Ext.Panel);

    and this .php file in wich a handle the reguest in the Data Base…
    the grid shows me the values at the first load… but i need to consult the DB with the value of ‘consult_V_D’…

    if u see a solution write me: rcgarcia09…@…rplibertad..icrt..cu

  5. Reginald Sophomore 21 October 2016 at 04:57 Permalink

    I totally agree with the all questions you raised. I am sure there are many people who are faced with the same problems I recently had. I couldn’t find By the way, if anyone is facing a problem of filling MHA Dodd-Frank Certification, I’ve found a template here https://goo.gl/HDg052. You also can esign the form and fax it.


Leave a Reply