Default Sorting for a Flex DataGrid
While working on the DeveloperCircuit Flex widget, I had the need to set a default sorting for a Flex DataGrid control. The standard control does not provide a mechanism to do this.
The Flex documentation suggests that you sort the underlying dataset, however I felt that this was very unsatisfactory. When you manually sort a DataGrid, the column which is being used to sort the data and the order of the sort, ascending or descending, is shown by the way of little black arrow in the column header. I felt that the default sorting should also be communicated to the user by this mechanism.
After some experimentation, this is the solution I came up with. There is a DataGrid event which is called when the user sorts a column. By announcing this event manually, once the underling data set has been returned by a call to a back end server, one can simulate the user action and set the default sorting of the DataGrid, complete with arrow. Example below:
<mx:RemoteObject id="someService" destination="ColdFusion" source="{this.someServiceLocation}" showBusyCursor="false" result="this.someDataGrid.dispatchEvent ( new DataGridEvent ( DataGridEvent.HEADER_RELEASE, false, true, 0, // The zero-based index of the column to sort in the DataGrid object's columns array. null, 0, null, null, 0 ) );" />

August 20th, 2007 at 11:56 am
Thanks for the tip, it worked nicely!
August 22nd, 2007 at 4:37 pm
+1
October 1st, 2007 at 9:58 pm
Works perfectly! Thanks. I’m surprised Flex doesn’t have this by default.
October 27th, 2007 at 4:35 pm
David you are a lifesaver. This has been driving me nuts for days. Thanks.
November 21st, 2007 at 10:05 pm
That just ended an hour of head-banging. Thanks!
November 26th, 2007 at 6:10 pm
Thanks for posting this, it’s EXACTLY what I needed!
December 4th, 2007 at 6:01 pm
Hi there, nice – i was working on this code for some time now in the hope to be able to also specify in which direction (ascending, descending) the sort on the grid is shown, but no luck
Did you manage to do it? Tnx
December 5th, 2007 at 10:44 pm
@Gregor – The only thing I can think of is to issues either one, or two DataGridEvent.HEADER_RELEASE events depending on the required sort order.
December 19th, 2007 at 6:29 pm
Thanks a lot mate! That’s just what i needed. So why the heck didn’t Adobe implement something like this?!
June 19th, 2008 at 10:36 pm
Thanks for the idea! I used it with the AdvancedDataGrid dispatching the event AdvancedDataGridEvent.SORT.
June 27th, 2008 at 3:13 pm
Thank you for this little snippet. It was indeed the answer to what it was I was looking for. As I am still new to Flex it took me a little bit to understand what it was that was taking place here. Once I did it was great. I made a slight modification to it so that it may be more easily reusable code by placing this in a function. The code is below. I hope that this helps others looking for this.
private function dgSort(dgName:Object, dgColumn:int):void
{
/**
* The dgSort functions requires two input items. The dgName which as the variable suggest
* is the name of the DataGrid and the dgColumn, DataGrid Column, to be sorted by the numbers.
* column numbering begins with zero.
*
* These input items are used with the DataGridEvent below and is dispatched (excuted). The
* DataGridEvent has a total of 9 values for successful operation. They are listed below in expanded detail.
*
* 1. type:String — The event type; indicates the action that caused the event. This is represented by the
* dgName input variable. The DataGridEvent.HEADER_RELEASE constant defines the value of the type property
* of the event object for a headerRelease event, which indicates that the user pressed and released the
* mouse on a column header
*
* 2. bubbles:Boolean (default = false) — Specifies whether the event can bubble up the display list
* hierarchy.
*
* 3. cancelable:Boolean (default = false) — Specifies whether the behavior associated with the event can
* be prevented.
*
* 4. columnIndex:int (default = -1) — The zero-based index of the column where the event occurred. This
* is represented by the dgColumn input variable.
*
* 5. dataField:String (default = null) — The name of the field or property in the data associated with
* the column.
*
* 6. rowIndex:int (default = -1) — The zero-based index of the item in the in the data provider.
*
* 7. reason:String (default = null) — The reason for an itemEditEnd event.
*
* 8. itemRenderer:IListItemRenderer (default = null) — The item renderer that is being edited or the
* header renderer that was clicked.
*
* 9. localX:Number — Column x-position for replaying columnStretch events.
*/
dgName.dispatchEvent(
new DataGridEvent
(
DataGridEvent.HEADER_RELEASE,
false,
true,
dgColumn,
null,
0,
null,
null,
0
)
)
}
June 30th, 2008 at 3:01 pm
Gabriel,
I would love to know how it is that you managed to get the AdvancedDataGrid to do a default sort. So far I have been having no luck with that one and it would be a gret help as the current project I am on has at least one ADG that will initial be sorted on at least 3 fields.
July 26th, 2008 at 2:25 am
Nicely done – thanks David and Bob (for the function). Small point for the noobs out there (which I fell foul of) … make sure you have the ‘import mx.events.DataGridEvent;’ defined otherwise the function bombs out with a [1120: Access of undefined property DataGridEvent.].
Small question – I’m using this to auto-sort a datagrid by date column – date info is stored in YYYY-MM-DD format so gets round any Flex date understanding nightmares. The dgSort function above sorts in ascending order initially whereas I want it in descending order (i.e. newest dates top). Is there any way to specify one of the parameters above to do this? At the moment my workaround is to call the dgSort twice but it would be nice to save some cpu cycles. Any ideas appreciated.
Thanks, Darrell.
August 15th, 2008 at 1:49 pm
Great! A simple solution for an annoying problem!
Thanks!!!
August 24th, 2008 at 7:12 am
Hi,
I am doing a server side sort and getting the new dataset on header release of a datagrid. But i am not getting the default sort arrow. If i dispatch a new data grid header release event in the result handler, it is going in an infinite loop.
please give some clues, i m new to flex.
Thanks,
Venkat.
September 19th, 2008 at 11:05 pm
Much thank you!! just saved my day =]
September 22nd, 2008 at 7:17 pm
Many thanks !! i’ve been searching for this for 2 days now. thanks for putting me outta my misery.
like Gabriel i dispatched AdvancedDataGridEvent.SORT event. using this on a Flex app.
October 11th, 2008 at 4:52 pm
This is excellent – however, it alternates between ascending and descending sort each time – a bit annoying!
December 2nd, 2008 at 7:34 am
Thanks
it works without any problems.
February 6th, 2009 at 2:10 pm
Excellent tip. Just what I needed. Anyone has a great idea of how do sort descending? I’ve modified the code to dispatch the event twice for descending sort order, but if anyone has a better way of doing it…?
public function dgSort(dgName : Object, dgColumn : int, descending : Boolean) : void {
for (var i : int = 0; i < (descending ? 2 : 1); i++) {
dgName.dispatchEvent(
new DataGridEvent (
DataGridEvent.HEADER_RELEASE,
false,
true,
dgColumn,
null,
0,
null,
null,
0
)
)
}
}
February 12th, 2009 at 1:44 pm
This is useful! Has anyone got example code of this sort using an AdvancedDataGrid?
Also does any clever flex person have an idea how i would sort the AdvancedDataGrid on the Branch column containing a date? Im pretty new to flex and this is really bugging me
Jess
x
March 25th, 2009 at 4:28 pm
Hi
I am stuck with server side sorting. below is the problem I am encountering.
1) I am able to populate the data into the datagrid but it doesnt show the sort icon by default .. How Can I make it show on the column I desire
2) I want to do server side sorting and override datagrid provided sort.How do I get the information if the user has clicked in asc order or desc order.
After I receive data from the server do I need to create the columns again or just refresg the data provider..
Any help will be greatly appreciated
Regards
May 18th, 2009 at 2:35 pm
I just stumbled upon this post when searching for DG sorting. Some of you have asked how to make this descending instead of ascending by default. The easy way (instead of firing this off twice), is to set the “sortDescending” property to “true” in the datagrid COLUMN.
Thanks for the help.
-chad
June 4th, 2009 at 2:40 pm
Serious life saver – thanks for this….
July 31st, 2009 at 12:47 am
Thanks so much! I ran into this problem after failing to apply a sort to the underlying data provider since the column I wanted to sort was derived from more than one field.
August 18th, 2009 at 12:40 pm
@Gregor, David
Use a variable sort direction and a sort compare function. Make the sort compare function to sort ascending or descending based on the sort direction value.
September 2nd, 2009 at 3:34 pm
Hi,
Thanks for the trick worked nicely for me
September 25th, 2009 at 2:04 pm
David, Bob Tate, thanks a lot!
good luck with your work.
November 29th, 2009 at 2:50 am
public static function sortDataGrid(dgGrid : Object, dgColumnName : String , descending : Boolean) : void {
var dgColumn:int=0;
for (var col : int = 0; col < dgGrid.columns.length; col++) {
var column:Object = dgGrid.columns[col];
if(column.dataField == dgColumnName){
var sortField:String = column.dataField;
var sortThese:Sort = new Sort();
sortThese.fields = [new SortField(sortField, true, descending)];
dgGrid.dataProvider.sort= sortThese;
dgGrid.dataProvider.refresh();
dgColumn = i;
break;
}
}
for (var i : int = 0; i < (descending ? 2 : 1); i++) {
dgGrid.dispatchEvent(new AdvancedDataGridEvent(AdvancedDataGridEvent.HEADER_RELEASE,false,true,dgColumn,null,0,null,null,0))
}
}
January 7th, 2010 at 9:12 pm
@Eirik
To sort descending, set sortDescending=”true” on the DataGridColumn or AdvancedDataGridColumn. When the default sort gets called, it will be descending.
Cheers!
January 20th, 2010 at 6:52 pm
Nice tip.. Thanks tons for all the time you have saved.
February 1st, 2010 at 11:45 pm
Thanks for the idea of dispatching the event. I used it with the trick of descending the column and it works as I wanted.
February 12th, 2010 at 10:19 pm
Let me throw my thanks into the mix. I used the dgSort function in the comments above with sortDescending and it did exactly what I needed. That said, it seems like this should be an inherent property of the DataGrid to allow you to specify a column to use for the initial sort. As we can see from these functions it is not hard to accomplish and it seems like a very common use case. Adobe Flex Components team, are you listening?
April 22nd, 2010 at 1:33 am
[...] Default Sorting for a Flex DataGrid | BealeARTS (tags: flex datagrid sorting automatic) [...]
May 20th, 2010 at 4:21 pm
Thanks….it really helped n what a cool way to do that !
June 22nd, 2010 at 1:04 pm
You can define the first sort like ASC or DESC setting the propertie sortDescending in datagrid. True for descending or false for ascending. I think that is a better solution than dispatch two events.
July 5th, 2010 at 4:54 am
Just wanted to say thanks for this, too. Bizarre that this is not a built-in feature, though…
July 13th, 2010 at 12:13 pm
Thanks a lot
July 21st, 2010 at 9:18 pm
Thank you so much! That’s a perfect little snippet I pasted right into my code.
July 29th, 2010 at 4:23 am
This neat hack is totally unnecessary if you use an instance of ListCollectionView as your dataProvider because you can accomplish this by setting the sort property of your collection as shown below. Your suggestion would also reset the sort column if/when data is reloaded from the server. Thus you should create your collection and set the default sort field during initialization, then populate your collection anytime data is loaded from an external source, which will preserve the user’s chosen sort columns when data is reloaded.
However, I’ve found that if you have to set a custom sort function, then the DataGrid and AdvancedDataGrid doesn’t show the ascending/descending marker by default even though the data is properly sorted. I tried your suggestion to see if it would resolve my issue, but unfortunately it does not work either.
[code]
import mx.collections.Sort;
import mx.collections.SortField;
import mx.collections.XMLListCollection;
private accounts:XMLListCollection;
private function init():void {
accounts = new XMLListCollection();
accounts.sort = new Sort();
accounts.sort.fields = [new SortField("name", true, false, false)];
accounts.refresh();
}
[/code]
If you want to try an awesome data grid, go to http://flexicious.com/Home/Demo.
September 30th, 2010 at 11:22 pm
Hi,
I want to sort a coulmn of a datagrid, by using predefined values..
i have values in datagridcolumn like ( ? , ! , *, *!, !?, *?…)
AND I WANT TO SORT THE GRID VALUE IN THE ORDER ( ! , *! ,!? , ? , *? , * )
cAN YOU GUYS HELP ME OUT..
January 13th, 2011 at 2:42 pm
It worked
May 11th, 2011 at 11:40 am
Great and simple solution.
Just one side note, if you change the dataprovider of the datagrid the sorting will be lost. In order to avoid this you can use a ListCollectionView as the dataprovider of the datagrid and assign your ArrayCollection data to the ‘list’ property of the ListCollectionView. Then if you need to change the dataprovider you only modify the list property and the dataprovider of the datagrid is not reset, and the sort is preserved.
May 17th, 2011 at 6:30 pm
Awesome! Thanks.