Hello. I have a new blog.

I've moved this blog to the following URL Kerkness.ca. Thank you for visiting, please update your bookmarks.

Thursday, October 2, 2008

Flex Tip : Use ObjectUtil for Alpha and Numeric sorting on a DataGrid

If you haven't taken the time to look at the features of Flex's ObjectUtil you should. Inside are a few handy methods which I see getting over looked.

Two of those methods are ObjectUtil.stringCompare and ObjectUtil.numericCompare. These methods make it simple to provide intelegent sorting on DataGrid columns.

Let's say you have a DataGrid that has one column full of ID# and another column full of people's names including both first and last names. Chances are the default sorting abilities of the DataGrid will not properly sort either column. The ID# would be sorted 1,10,11,12... instead of 1,2,3,4,5... and the column of names would sort by the first name and not the last name.

Lucky the DataGridColumn allows you to set a custom sort function via the property sortCompareFunction. For example look at these two DataGridColumns.

<mx:DataGridColumn headerText="ID#" dataField="contactid" sortCompareFunction="sortContactId"/>
<mx:DataGridColumn headerText="Name" dataField="full_name" sortCompareFunction="sortLastName">
 <mx:itemRenderer>
  <mx:Component>
    <mx:Label paddingLeft="5" text="{data.firstname} {data.lastname}" />
  </mx:Component>
 </mx:itemRenderer>
</mx:DataGridGolumn>

The first column is for the ID# of a contact, the second column uses an itemRenderer and displays both the firstname and lastname for the contact. Each column defines it's own sortCompareFunction. Both functions make use of methods from mx.utils.ObjectUtil.

private function sortLastName(obj1:Object,obj2:Object):int
{
   var value1:String = (obj1.lastname == '' || obj1.lastname == null) ? null : new String(obj1.lastname);
   var value2:String = (obj2.lastname == '' || obj2.lastname == null) ? null : new String(obj2.lastname);
   return ObjectUtil.stringCompare( value1, value2, true );
}
private function sortContactId(obj1:Object,obj2:Object):int
{
   var value1:Number = (obj1.contactid == '' || obj1.contactid == null) ? null : new Number(obj1.contactid);
   var value2:Number = (obj2.contactid == '' || obj2.contactid == null) ? null : new Number(obj2.contactid);
   return ObjectUtil.numericCompare( value1, value2 );
}

These functions are pretty straight forward.  sortLastName function uses stringCompare method to compare the lastname from two objects. The flag 'true' is set to make sure that the comparison is case insensitive. The sortContactId function uses the numericCompare method to compare the contactid from two objects.

No comments:

Post a Comment

Thank you for the comments.