07 March 2012

Custom sort names EXTJS 4 grids

I build grids all the time in EXTJS 4 and they are usually dealing with a ton of data so server side sorting is a must. EXTJS sends the header name of the grid column and and the sort direction to the server by default. That's all fine and dandy but most of the time my column header names differ from the names I need to send to the server for proper sorting. So here is what I came up with.

First I add a config called customSort to my column configs. The customSort will be the value that is sent to the server when clicking the grid column header.

 1 var gridColumns = [{
 2     text: 'Id',
 3     dataIndex: 'id',
 4     width: 75
 5 },{
 6     text: 'Queue Cat',
 7     dataIndex: 'queue_cat',
 8     width: 100,
 9     customSort: 'DocumentQueueCategory.name'
10 },{
11     text: 'Queued to Customer',
12     dataIndex: 'queued_to_customer',
13     flex: 1,
14     customSort: 'User.lastname'
15 },{
16     text: 'Locked By',
17     dataIndex: 'locked_by',
18     width: 150,
19     customSort: 'LockedBy.lastname'
20 },{
21     text: 'Last Act. Admin',
22     dataIndex: 'last_activity_admin',
23     width: 150,
24     customSort: 'LastActAdmin.lastname'
25 },{
26     text: 'Created',
27     dataIndex: 'created',
28     width: 110,
29     format: 'm/d/y g:i a',
30     xtype: 'datecolumn'
31 },{
32     text: 'Modified',
33     dataIndex: 'modified',
34     width: 110,
35     format: 'm/d/y g:i a',
36     xtype: 'datecolumn'
37 }];

Then in the store for my grid I add some code to the before load listener to check for a customSort param on each column. If the param is found the store will send the customSort value to the server, if no customSort value is found it will send the column header name as normal.

 1 listeners: {
 2   beforeload: function (store, options) {
 3     if(store.sorters.items[0]){
 4       var oldSortParam = store.sorters.items[0].property;
 5       for(var i=0; i < gridColumns.length; i++) {
 6         var currentCol = gridColumns[i];
 7         if(currentCol.sortable && currentCol.customSort && 
 8            currentCol.dataIndex == oldSortParam) {
 9              store.sorters.items[0].property = 
10              currentCol.customSort;
11              break;
12         }
13      }
14     }
15   }
16 }
comments powered by Disqus