A couple of months ago I posted an example that I wrote to show how to filter a Flex DataGrid on the fly. This afternoon a user asked me how to do filtering using date ranges, allowing a date start and end to be specified so as to filter only data that falls within the specified range.
So, here is an updated example. In the interests of simplicity a local ArrayCollection is used. I have added a Date object member named hired (if you were retrieving data from a back-end like ColdFusion then you would likely return a date type which would be converted to an ActionScript Date class so as to be able to easily perform date calculations).
The UI has two DateField controls, startDate and endDate, and a change to either forces a refresh and the filterFunction is applied. The ArrayCollection filterFunction simply checks that the hired date falls between startDate and endDate (allowing null in case no date is selected).
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
layout="vertical"
creationComplete="initApp()">
<mx:Script>
<![CDATA[
// On startup
public function initApp():void
{
// Set filter function
// Be careful to set filterFunction
// only after ArrayCollection has been
// populated.
myData.filterFunction=processFilter;
}
// Filter function
public function processFilter(item:Object):Boolean
{
var result:Boolean=false;
// If start date is null or <= hire date
// and end date is null or >= hire date
if ((dateStart.selectedDate == null
|| dateStart.selectedDate <= item.hired)
&& (dateEnd.selectedDate == null
|| dateEnd.selectedDate >= item.hired))
{
result = true;
}
return result;
}
]]>
</mx:Script>
<!-- Data (use ArrayCollection) -->
<mx:ArrayCollection id="myData">
<mx:source>
<mx:Object name="Ben Forta"
location="Oak Park, MI"
phone="(248)555-5555"
hired="{new Date(2002, 8, 17)}" />
<mx:Object name="Jane Doe"
location="New York, NY"
phone="(212)555-1234"
hired="{new Date(1999, 12, 16)}" />
<mx:Object name="Jim Jones"
location="Atlanta, GA"
phone="(414)555-1212"
hired="{new Date(2003, 4, 21)}" />
<mx:Object name="Roberta Roberts"
location="Chicago, IL"
phone="(312)555-4321"
hired="{new Date(2002, 3, 8)}" />
<mx:Object name="Steve Stevens"
location="Boston, MA"
phone="(617)555-5656"
hired="{new Date(2006, 6, 14)}" />
</mx:source>
</mx:ArrayCollection>
<!-- UI -->
<mx:ApplicationControlBar width="100%">
<mx:Label text="Show from"/>
<mx:DateField id="dateStart" change="myData.refresh()" />
<mx:Label text="to"/>
<mx:DateField id="dateEnd" change="myData.refresh()" />
</mx:ApplicationControlBar>
<mx:DataGrid dataProvider="{myData}"
width="100%" height="100%">
<mx:columns>
<mx:DataGridColumn headerText="Name"
dataField="name"/>
<mx:DataGridColumn headerText="Location"
dataField="location"/>
<mx:DataGridColumn headerText="Phone"
dataField="phone"/>
<mx:DataGridColumn headerText="Hired"
dataField="hired"/>
</mx:columns>
</mx:DataGrid>
</mx:Application>
There are no comments for this entry.
[Add Comment]