Flex 3: Forcing Numeric Sort of XML Data in a Data Grid
Recently I've ran into some problems with AdvancedDataGrids in Flex with data loaded from a hierarchical data provider built from an XML object. When you try to sort on a column with numeric values, the data grid does not sort the values numerically. Instead it sorts them lexicographically. This is because Flex 3 treats all the attributes of an XML node as strings. So if you have an/some attribute(s) that is numeric amongst all of your nodes, Flex treats these as strings when sorting. It is apparently not smart enough to realize that the values are numeric and should be sorted as such.
Unfortunately, Flex doesn't appear to provide an easy way to say that a certain column contains numeric values. A simple attribute of the AdvancedDataGridColumn element called valueType or something along those lines that you could simply say valueType="Number" would be incredible, but that functionality does not exist. So what you have to do is write a sortCompareFunction for each of these columns. Well, if you have a bunch of different columns you would usually have to write one sortCompareFunction for each column.
That could get tedious and time consuming. Instead, declare the following function:
private function xmlDataGridNumericSorter(field:String):Function
{
return function (xml1:Object, xml2:Object):int
{
var diff:Number = ((Number)(xml1.attribute(field)) - (Number)(xml2.attribute(field)));
return (diff > 0) ? 1 : ((diff < 0) ? -1 : 0);
}
}
What this function does is return a compare function that would compare the values of two XML node's attribute (field:String). So what you do from there forth is loop over your columns that are numeric and do the following to each column, referenced in the example as col:
col.sortCompareFunction = xmlDataGridNumericSorter(col.dataField);
After that each of the columns you modified in this way will have a sortCompareFunction built to compare two XML nodes' respective attributes numerically. Keep in mind with the above code that if your column's dataField is prefixed with an at sign (@), which it very well should since you're probably referencing an XML attribute, you will need to remove it when you are passing the dataField into the xmlDataGridNumericSorter function by adding .replace("@","") after col.dataField.
I hope this helps people as much as it has helped me in the past few weeks!
Nov20


