Uncommented Bytes

Thursday, February 28, 2008

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'}

2 Comments:

  • Well, you probably just saved me a few hours. Thanks!

    By Anonymous Anonymous, at 13 June, 2008 15:50  

  • If you had the city index in your data model you could have bound the column to your cityIndex and used a column renderer to display the city name instead of the index.

    var record = Ext.data.Record.create([
    {name: 'city'},
    {name: 'cityIndex', type: 'int'}]);

    ...
    function cityRenderer(value, meta, record) {
    return record.get('city');
    }
    ...

    var cm = new Ext.grid.ColumnModel({
    columns: [{
    header: 'City', renderer: cityRenderer, dataIndex: 'cityIndex'}];

    By Anonymous Anonymous, at 18 November, 2009 10:37  

Post a Comment

Links to this post:

Create a Link

<< Home