Skip to content
November 24, 2010 / edeustace

Sorting nested fields in a DataGrid

The Flex DataGrid doesn’t provide an out of the box way of sorting against nested objects.
The best way to do it is to use a custom sort against the dataprovider. By doing this you can sort by multiple fields too.

Here is an example of sorting a datagrid on nested fields (right-click for the source code):

http://ed.eustace.net/flex_samples/complex_sort_dg/Main.html

To aid with nested sorting, I’ve created a *NestedSortField*, which takes a period delimited string and then checks for nulls on the object all the way down.
For example: if you supply the NestedSortField a name of “person.name.firstName”, it’ll first check for null against obj.person, then against obj.person.name, then obj.person.name.firstName etc.

There are a few other things to note, that you can see in the source. But in a nutshell, you need to override the headerRelease event and disable the DataGrid default sort by calling event.preventDefault(). However when you do this, the sort arrows in the DataGrid don’t get updated. To fix this you need to override the DataGrid and add two setters so set the Sort direction and Sort index.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: