Custom sort key with Ext JS Grids
I’ve begun using Ext JS in the
last few days. I’m very impressed by the professionalism and api documentation, but there is
still a lot to be desired as far as installation and initial setup docs.
Anyway… I spent a couple hours trying to track down a way to sort a column in my
GridPanel by a value other than its text. That is, I want the column to sort on a keyed index
that is different than just alphabetically sorting the text value. This seemed like something
that should be built into the framework, like with Displaytag,
but unfortunately it is not!
Finally, after digging through the API
docs, google searches, and ext forum searches, I found a
solution.
Basically you have to define a custom sortType on
the Record. Here is my example code that sorts cities on an arbitrary “FavoriteCity”
index:
function sortFavoriteCities(cityName) {
var sortOrder = {‘New York’:0, ‘London’:1, ‘Chicago’:2, ‘Paris’:3};
return
sortOrder[cityName];
}
var reader = new
Ext.data.ArrayReader({}, [
{name: ‘city’, sortType: sortFavoriteCities},
{name: ‘state’},
{name: ‘country’}
]);
I just hope that this helps someone else save a few
hours! And, it would be very nice if the Ext JS developers would add a helper method where we
could just pass the “sortOrder” array into the sortType field as a custom sort order. {name: ‘city’, sortType:
{‘New York’:0,
‘London’:1, ‘Chicago’:2, ‘Paris’:3}
}
Or extend that a step farther and allow sortType to use a different record as the sort
key, like
{name: ‘city’, sortType: ‘cityIndex’}, {name:
‘cityIndex’}