Creating MDataGrid date filter

In this post I will describe how to create custom filter for MDataGrid (my extension of Flex 3 DataGrid described in one of the previous posts and hosted on http://code.google.com/p/reusable-fx/). I will guide you through creation of date filter as an example.

I consider extensibility one of the most important feature of well designed reusable component and that’s why I am trying to make process of creating new MDataGrid filters as straightforward as possible.

Following “Favor object composition over class inheritance.” rule I decided to split filtering functionality among a number of classes rather than write another thousand lines of DataGrid code. At the first glance the solution may look complicated but after understanding responsibilities of “filters” and “filter editors” it is really straightforward.

Filter editors are the components displayed below column header after clicking filter button. Filter editor know nothing about business logic of filtering, their only responsibility is to present current state of the filter to the user and modify filter according to users actions. Filter editor may be any component implementing IColumnFilterEditor interface. The default implementation of this interface is FilterEditorBase class extending Box which is used as a base class for all standard MDataGrid filter editors. In the presented example we will create filter editor in MXML extending FilterEditorBase class.

Filter classes are where actual filtering takes place, they implement filterFunction which is used to eliminate items from MDataGrid data provider. Filters are also responsible for examining MDataGrid and presenting information about MDataGrid content to filter editors. In our example filter will present minimum and maximum dates found in given column. All filters extends ColumnFilterBase class.

To implement date filtering mechanism two classes have to be implemented: filter class (DateRangeFilter) and filter editor class (DateChooserFilterEditor).

DateRangeFilter

DateRangeFilter extends ColumnFilterBase class and defines four fields: dataMinimum, dataMaximum, minimum and maximum.

dataMinimum and dataMaximum represents a earliest and latest dates found in MDataGrid. These fields are updated by updateOriginalDateRange() function.

minimum and maximum defines the range of dates which will be displayed in MDataGrid. By default minimum is set to dataMinimum and maximum is set to dataMaximum which means that all data are displayed (filter is inactive). It is important to call commitFilterChange() function inside minimum/maximum setter to inform MDataGrid that filter value have changed.

DateRangeFilter also overrides two functions defined in ColumnFilterBase:

isActive getter checks if filter is active i.e. if it may eliminate any items form MDataGrid. In our case isActive getter simply checks if minimum and maximum differs from dataMinimum and dataMaximum.

override public function get isActive():Boolean
{
    return (minimum != dataMinimum || maximum != dataMaximum);
}

filterFunction checks if item passed as an argument should be eliminated. First date displayed in column associated with this filter is extracted from given item and then it is compared against minimum and maximum. If the value is within the range true is returned (item is not eliminated) other ways false is returned (item is filtered out). If no date is fond for the given item true is returned. filterFunction is called many times for every MDataGrid item so it should not be computationally expensive.

override public function filterFunction(obj:Object):Boolean
{
    var value:Date = itemToDate(obj);
    
    if (value)
    {
        if (minimum && value < minimum)
        {
            return false;
        }
        if (maximum && value > maximum)
        {
            return false;
        }
    }
    return true;
}

You can find two additional functions in DateRangeFilter code: itemToDate() is responsible for extracting date from data item and originalCollectionChandeHandler() refresh dataMinimum and dataMaximum when MDataGrid original collection (copy of data provider) changes.

DateChooserFilterEditor

Good news: creating filter editors in MXML is much simpler than coding filter and the effect is instantly visible!

To make curly brackets binding simpler it is good idea to create strongly typed, bindable reference to filter instance edited by filter editor. The code below is the only code placed in <script> tag of our filter editor:

[Bindable]
protected var filter:DateRangeFilter;

override public function startEdit(column:MDataGridColumn):void
{
    super.startEdit(column);
    if (!column.filter || !column.filter is DateRangeFilter)
    {
        column.filter = new DateRangeFilter(column);
    }
    filter = column.filter as DateRangeFilter;
}

All you have to do now to create cool filter editor is placing MXML components with appropriate bindings and inline event handlers. Below you can see my proposals how date filter editor may look like.

The simple DateChooserFilterEditor consists of two DateChoosers and reset button.
View source is enabled, you can download zipped sources from here.

For better experience open example in separate window.

To save some space I have replaced DataChoosers with DateField and created DateFieldFilterEditor.
View source is enabled, you can download zipped sources from here.

For better experience open example in separate window.

Of course dates may be filtered in many different ways. For example date filter editor may consist of two NumericSteppers to select years. I hope now you can create such filter editor by yourself.

If you have any questions or suggestions don’t hesitate to add a comment!

Share on Google+Share on FacebookShare on LinkedInPin on PinterestTweet about this on Twitter

53 thoughts on “Creating MDataGrid date filter”

  1. Hi,
    I have a ComboBox component with ChecBoxes to change column visibility, I will publish it on this blog when I have a while to clean up the code.

    For now, probably the simplest solution will be to use Repeater with DataGrid columns as dataProvider and CheckBox inside. Something like code below (assuming dataGrid is standard DataGrid or MDataGrid instance):

    <mx:Repeater id="columnsRepeater" dataProvider="{dataGrid.columns}">
        <mx:CheckBox 
            label="{columnsRepeater.currentItem.headerText}"
            selected="{columnsRepeater.currentItem.visible}"
            data="{columnsRepeater.currentItem}"
            change="{event.target.data.visible = event.target.selected}" />
    </mx:Repeater>
    
  2. Thanks! The Repeater element works well.

    Regarding date function above, i have an external file with elements

    name1

    {new Date(1984,11,04)}

    All elements above the “…” work fine but the last ‘date’ entry does not parse. I tried modifying the entry including removing braces and NEW tag. Can your date filter work on external loaded XML file like above? thanks in advance for your reply, and keep up the good work!

  3. my entry got truncated:

    i was asking whether the date object can load from an XML file and i put some pseudocode:

    players
    player
    MB_OriginDate /MB_OriginDate
    /player
    /players

  4. If you are using XML data provider (not ArrayCollection declared in MXML) you should use simple MM/DD/YYYY format without braces or new keyword. Unfortunately there is a minor bug in the sources in this post so that it will not work. I will submit the bugfix on http://code.google.com/p/reusable-fx/ tomorrow.

  5. How can I force to call the filter first time the page is loaded. I need this because if I update one record using filters, after the update is performed the filters are lost(they look like set but not aplied)

  6. AdvancedDataGrid is the totally different component than DataGrid (they don’t have a common base class) so my filtering solution will not work with AdvancedDataGrid. Moreover the code of ADG is quite dirty so I’m not eager to extend it.

  7. I want the same filtering functionality on a map,specifically iLOG Elixir Map.

    So here is the scenario,there is filter data, instead of a data grid I have a map that updates based on the filters.

    Can you throw some light how can i do this?

    Your help is greatly appreciated!

  8. Hi, I too need filtering options for Advanced Data Grid with hierarchical data source, can anyone please help, its urgent need… THANKS A LOT IN ADVANCE

  9. Hi,
    great component ! 🙂

    Is it possible to reset the filter or force the filter (useful if the dataprovider has been updated) ?

  10. Hi Iwo,

    great component, really nice coding but I must say to be disapointed, as there is no solution for Advanced Data Grid… 😉 I try to workaround with filterFunction functionality as my dataprovider is an array collection.

  11. Hi icemaker,
    I have this functionality implemented but haven’t committed it yet (I have to clean it up a little).
    I’ll let you know when it will appear in on google code page.

  12. Hi Antoni,
    Unfortunately AdvancedDataGrid is totally independent from DataGrid and it doesn’t seams trivial to port functionality between them.
    Moreover, as mentioned on flexcoders,
    the code quality of AdvancedDataGrid is worse than DataGrid so that it is much harder to extend.

  13. Hi again,

    I’ve just noticed that the property headerWordWrap=”true” does not work anymore for colums when using MDataGrid.
    I don’t know if it is a bug or it is intended.
    Do you have any solution to this problem ?

  14. Please is there any chance to change format date for sorting to be DD/MM/YYYY ?

    I was looking but i was unable to find anyting….

  15. Hi Serhio,

    If you mean format inside filter drop down it is based on DateField and the date format can be changed by modifying formatString property inside filter editor class.

    But probably the better solution would be to use locales with the correct date format defined. The date format is defined inside SharedResources.properties resource bundle.

  16. hi!

    first of all: excellent component, nice code, very easy to use… really great!
    i’m missing one thing though… is there any news on the filter reset functionality?

    thanks
    breeze

  17. thank you very very much for the quick response… working great!

    maybe you can help me again with another issue: have you encountered any problems with manipulation of dataprovider (arraycollection) after sorting? after i sort a column, adding a row (addItem on the arraycollection) for example will through some errors (null pointer at ListCollectionView.as:954). without sorting everything works fine… also the global search functionality behaves weird after sorting.

    hints would be greatly appreciated!

    greetz
    breeze

  18. Hi Todd,

    If you don’t want a column to be filterable simply use DataGridColumn (as with standard Flex DataGrid) instead of MDataGridColumn.
    Cheers, Iwo

  19. This is great component, but I’m pretty new to this aspect of flash/flex programming and I was curious how to do something, if it were even possible.

    Say I wanted to add this grid into a wrapper mxml component along with some additional features like export functionality… basically i’m looking for a method to have a root component such as

    <dgWrapper allMyVariables>

    <MDataGrid usesVariablesFromDgWrapper>

    </MDataGrid>

    <dgTitleBar usesVariablesFromDgWrapper />

    </dgWrapper>

    or something to the effect of having to rewrite as minimal code as possible to implement the component.

    The thing that is throwing me off is since the dataGridColumns are a child of the datagrid, i’m uncertain how to write an mxml component that is basically a box, with a datagrid contained in it, and a applicationControlBar, and allow for the defining of the columns within the datagrid from the application calling it perspective. If this is making no sense at all, i understand completely 😛

  20. Hi Kritner,
    Sure it makes sense! You can do it in several ways. I think that following one is the simplest.

    Inside <Script> block declare public bindable variable of type Array and bind MDataGrid column property to it.

    <dgWrapper allMyVariables> 
    <Script> 
    [Bindable]
    public var columns:Array;
    </Script> 
    <MDataGrid usesVariablesFromDgWrapper columns="{columns}"> 
    </MDataGrid> 
    <dgTitleBar usesVariablesFromDgWrapper /> 
    </dgWrapper> 
    

    And than, use your dgWrapper like this:

    <dgWrapperComponent> 
        <columns> 
          <MDataGridColumn properties /> 
          <MDataGridColumn properties /> 
        </columns> 
    </dgWrapperComponent> 
    

    Alternatively you can create MDataGridColumns in ActionScript (inside your component Script block) based on some of its properties but it would probably be more complex solution.

    Hope this is of any help for you.

  21. @Iwo Banas
    do you have an example of creating the columns through the use of an array? Having trouble finding info on it.

    Would itemRenderers still be possible through setting columns through this method?

  22. @Kritner Sicarius
    I’ve figured out my issue with the array… still am unsure about how i would accomplish itemRenderers, and I’m also having trouble applying a filterEditor to a column.

    var column:MDataGridColumn = new MDataGridColumn();

    column.filterEditor = IFactory(DateFieldFilterEditor(column));

    not getting any compile errors with that, but the DG is not displaying properly when i have that line in, if i comment it out it seems to work fine (but i don’t have the filterEditor i want)

  23. Hi Iwo! You did a really good job! Thanks for this excellent component!
    I have only one question:
    Is there a way to dynamically set the filter from outside the grid? So that the data is already filtered by defined criteria when the grid is displayed.

    Thanks in advice, Uwe

  24. Hi Iwo, thanks for you wonderful component, Is there’s a way to use the component filtering function in AIR? by the way i am using the swc version of reusableFX.

    Thank you very much.

  25. Hi,

    Cool component.

    I am using your MDatagrid component. It works fine. But I am facing a problem. When I change the data provider, the values in the filter editors are not reset. Can u help me in this?

  26. Hi,
    Great component. I am not able to see the style change from default to red filter button when filter is activated. I have followed your example. Can you suggest some pointers?
    Thanks
    Tommy

  27. Hi,
    Thanks for your great control. I used it for many applications, but I have a problem: style of filter button can’t change(filter.png and filter_active.png) when I upgrade my project to sdk 3.5: The color of filter button can’t change from white to red. It will be better if you solve this problem. Thanks!
    NCT

  28. What steps will reproduce the problem?
    1.Have a check box on first column and map it to boolean field from the VO Object
    2. Have column with date and have Multiple duplicate values in that column
    3. apply sort on the date column
    4. Select the check box and change the bollean field in VO based on user selection

    What is the expected output? What do you see instead?
    Check box should be selected. Instead selected row is moving to top or bottom in its group of common values.(resorting, and not able to preserve previous order among the common values(dates)

    What version of the product are you using? On what operating system?
    ReusableFx-20090901.zip , Windows XP

    Please provide any additional information below.
    As soon as updating the VO, it is firing collection change event and trying to resort on column and not able to preserve the previous order amond duplicate dates.

  29. Data grid rows are rearranged after user selected a row using check box
    What steps will reproduce the problem?
    1.Have a check box on first column and map it to boolean field from the VO Object
    2. Have column with date and have Multiple duplicate values in that column
    3. apply sort on the date column
    4. Select the check box and change the bollean field in VO based on user selection

    What is the expected output? What do you see instead?
    Check box should be selected. Instead selected row is moving to top or bottom in its group of common values.(resorting, and not able to preserve previous order among the common values(dates)

    What version of the product are you using? On what operating system?
    ReusableFx-20090901.zip , Windows XP

    Please provide any additional information below.
    As soon as updating the VO, it is firing collection change event and trying to resort on column and not able to preserve the previous order amond duplicate dates.

  30. Hi,
    Thanks for the great component. My application has more than 200 results displaying in the datagrid, is there anyway I can separate them in pages?

    Thanks,
    DE

  31. Hi,your component is very gud.But I want to add footer in the datagrid
    where i can get sum of perticular column.can u suggest me a any idea.

  32. Hi Iwo,

    First of all, I would like to say this a great component, though, I had a little problem using the MultipleChoiceFilterEditor, the supposedly list of CheckBoxes became Toggle Buttons. This happens when I used SDK 4 and loaded the MDataGrid inside a Module. Can you give me some pointers to fix it?

    Thank you in advance.
    Norbert

  33. It is very useful component. I got stuck with problem in date filtering that on loading i have to display start date and end date for one month duration from the latest date. any help.. thx in advance..

  34. Have a look at this comment.
    You should be able to initialize column.filter with DateRangeFilter and set minimum/maximum in a similar way.
    You may need to assign the id to your column so that you can easily access it.

  35. Hi all,

    I’m using that Datagrid and I want to update a paginator linked to de arraycollection every time the filters selection change, but I don’t know what event I must capture.

    Can anybody help me???

  36. Hi Iwo you mentioned on your post above that you have implemented the resetAllFilters() function to reset any filtering made on the datagrid, can you please point us to the URL where we can download that version of MDataGrid that has the resetAllFilters() function. Thank you very much for sharing this great component.

    sam

  37. Hi, We are using your component. Want blank values in multiple options filter. Also want to do server side filtering and sorting. Can you please send the link to most up to date source code. Thanks, Jim

  38. Hi Iwo,

    I used your date filter in my application. However my filter object is coming as null (checked it in debug mode). I am getting error like

    TypeError: Error #1009: Cannot access a property or method of a null object reference.

    Kindly help.

    I am using FlashBuilder 4.6

    Anurag

  39. Great work, now i implement for Flex 4.5 and Arabic layout, requires layoutDirection=”rtl”, but i found ut that drop down filter box not appear, seems to me it tries to allign to right edge of the table, all filters, not appear in right position, do you know how to resolve this ?

Leave a Reply

Your email address will not be published. Required fields are marked *