Search code examples
javaextjsextjs4

ExtJS grid filter automatically creating the list of possible options from the data in the store


There is a Store defined:

var myStore = Ext.create('Ext.data.JsonStore', {
    autoLoad: true,
    autoDestroy: true,
    model: 'Project',
    proxy: {
        type: 'ajax',
        url: '/project/list',
        reader: {
            type: 'json',
            root: 'data'
        }
    },
    remoteSort: false,
    remoteFilter: false
});

that is used by the grid panel:

Ext.create('Ext.grid.Panel', {
    store: store,
    columns: [{
            dataIndex: 'option',
            text: 'Option',
            filter: {
                type: 'list',
                store: optionStore // how this should be defined?
            }
    }], // many columns with 'list' filters 
    features: [{
        ftype: 'filters',
        local: true
    }]
});

Once the data is loaded from the server all the operations (sorting, filtering) are performed locally. All the values displayed in the columns are from a fixed set of values, so the filters' type is list. Is it possible to automatically generate filters from the values in the store (myStore)?


Suggested solution:

columns: [{
    dataIndex: 'name',
    text: 'Name',
    filter: {
        type: 'string'
    }
}, {
    dataIndex: 'client',
    text: 'Client',
    filter: {
        type: 'list' // caused the filtering to be disabled
    }        
}, {
    dataIndex: 'domain',
    text: 'Domain'
}]

Solution

  • So myStore is store of the grid right? If so, add this method to it:

    ,getUniqueValues:function(field) {
        var  me = this
            ,results = {}
        ;
    
        me.each(function(record){
            var value = record.get(field);
            results[value] = {};
            results[value][field] = value;
        });
    
        return Ext.Object.getValues(results);
    } // eo function getUniqueValues
    

    Now, listen to myStore load event (if it is remote) and call getUniqueValues in the listener passing the field name you want the unique values from. Having the unique values array, you can do whatever you want to do with it, e.g. load to a combo, use as list for grid filter, etc.

    Of course you can modify the format of the returned data by changing the method itself.