2012/02/18

[ExtJS] Keeping Grid Selections After a Store Reload in Grid

In some cases, we have no idea what time the data in grid is out of date. In order to get the last data in server, it’s necessary reload store in grid periodically. However, after a single/multiple slelection grid reload, the selection state will be lost (i.e., No records are selected).

image

A checkbox selection example

To slove this probelm, firstly, we have to push each selected records into grid’s variable selectedRecords whenever 'selectionchange' event is fired from grid. Something like this:

Ext.each(selecteds, function(selected) {
     me.selectedRecords.push(selected.index); 
});

Secondly, restore the selection state by selecting the records recored in selectedRecords whenever 'datachanged' event is fired from store (i.e., data is reloaded from server) is fired.

Ext.each(me.selectedRecords, function(r) { 
     me.getSelectionModel().select(r, true);
});
The complete example code is shown below. It’s tested under ExtJS4.0.

SelectionStatefulGrid.js

Ext.define('Vos.view.SelectionStatefulGrid', {
    extend : 'Ext.grid.Panel',
    selType : 'checkboxmodel',
    selModel : {
        mode : 'MULTI'
    },
    store : 'myStore',
    columns : [
        {
            header : 'my date',
            dataIndex : 'data'
        }
    ],
    initComponent : function() {
        var me = this;
        me.callParent();  
        me.selectedRecords = [];
        me.unlockState = false;
        // Push the the selection state into selectedRecords
        me.on('selectionchange', function(selectionModel, selecteds) {
            if (me.selectedRecords != null && me.unlockState) {
                me.selectedRecords = [];
                Ext.each(selecteds, function(selected) {
                    me.selectedRecords.push(selected.index);
                });
            }
        });
         // Select the records in selectedRecords
         me.getStore().on('datachanged', function(store, records) {
            Ext.each(me.selectedRecords, function(r) {
                me.unlockState = false;
                me.getSelectionModel().select(r, true);
            });
            me.unlockState = true;
        });        
    }
});

沒有留言:

台灣好行:後慈湖、大溪老街半日遊

要搭台灣好行 慈湖線 (票價100)的朋友,可以在【中壢火車前站】出口,往左邊直走5分鐘到【桃園客運總站】搭乘。搭車到最後一站【慈湖】後可以看到導覽服務站。後慈湖算是管制區,需要先 上網申請 才可以進入,如果是搭台灣好行的話,可以直接在服務站登記候補。假日通常都是人滿為患,建議如...