Friday 18 June 2010

Action script Date Data Provider

I had a requirement to show 2 drop downs for From and To selection of months and year, values like this:

Jan, 2010
Feb, 2010 and so on

And I used the following class to get this working like this.

Based on the class from
http://flexdateutils.riaforge.org/

public function getListOfMonthsAndYear(date:Date,noOfMonths:int = 12):ArrayCollection
{
var monthArr:ArrayCollection = new ArrayCollection();
var obj:Object = new Object();
var dt:Date = new Date();
var n:int = 0;
for (var i:int = noOfMonths; i >= 0; i--)
{
n++;
dt = DateUtils.dateAdd(DateUtils.MONTH,-i, date);
obj = new Object();
obj['label'] = DateUtils.dateFormat(dt,'MMM YYYY');
obj['data'] = DateUtils.dateFormat(dt,'YYYYMM');
obj['no'] = n;
monthArr.addItem(obj);
}
return monthArr;
}

Then I created filtering on the second drop down to remove all the entries which are not relevent, like if you select in your From combo, say Month March, 2010 then you don't want user to select Jan, 2010 in To combo as that would be wrong.

Here is the filter I created on Array Collection:

/**
* From Month Change Handler
*/
private function onFromMonthChange(event:Event):void
{
var comboBox:ComboBox = null;

comboBox = event.currentTarget as ComboBox;
this.currFromMonthNo = Number( comboBox.selectedItem.no );
this.monthToDP.filterFunction = this.toMonthFilter;
this.monthToDP.refresh();
if (this.monthToDP.length > 0) this.monthsTo.selectedIndex = 0;
this.criteria.monthFrom = this.monthsFrom.selectedItem.data;
this.criteria.monthTo = this.monthsTo.selectedItem.data;
}

private function toMonthFilter(obj:Object):Boolean
{
return Number(obj.no) >= this.currFromMonthNo;
}

Actually I used a trick to store number starting from 1 to end of the list in both collections and removed the items with the no's above the selected one from To combo list

Enjoy

No comments: