Avg. Rating 4.0

Problem

You want to filter the contents of a DataGrid control (or any control using an XMLListCollection as a data provider) based on user input.

Solution

The following example shows how you can filter an XMLListCollection collection by using regular expressions in Flex.

Detailed explanation

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2009/04/01/filtering-an-xmllistcollection-using-regular-expressions/ -->
<mx:Application name="XMLListCollection_filterFunction_RegExp_test"
        xmlns:mx="http://www.adobe.com/2006/mxml"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            private function textInput_change():void {
                if (textInput.text.length == 0) {
                    xmlListColl.filterFunction = null;
                } else {
                    xmlListColl.filterFunction = xmlListColl_filterFunc;
                }
                xmlListColl.refresh();
            }

            private function xmlListColl_filterFunc(item:Object):Boolean {
                if (textInput.text.length == 0) return true;
                var f:String = "ig";
                var wasRegExp:RegExp = new RegExp(textInput.text, f);
                var nowRegExp:RegExp = new RegExp(textInput.text, f);
                var wasMatch:Boolean = wasRegExp.test(item.@was);
                var nowMatch:Boolean = nowRegExp.test(item.@now);

                return (wasMatch || nowMatch);
            }
        ]]>
    </mx:Script>

    <mx:XML id="nodesXML" source="nodes.xml" />
    <mx:XMLListCollection id="xmlListColl"
            source="{nodesXML.node}"
            filterFunction="xmlListColl_filterFunc" />

    <mx:ApplicationControlBar dock="true">
        <mx:Form styleName="plain">
            <mx:FormItem label="Filter:">
                <mx:TextInput id="textInput"
                        change="textInput_change();" />
            </mx:FormItem>
        </mx:Form>
    </mx:ApplicationControlBar>

    <mx:DataGrid id="dataGrid"
            dataProvider="{xmlListColl}"
            verticalScrollPolicy="on"
            width="100%"
            rowCount="10">
        <mx:columns>
            <mx:DataGridColumn dataField="@was" headerText="Was:" />
            <mx:DataGridColumn dataField="@now" headerText="Now:" />
        </mx:columns>
    </mx:DataGrid>

</mx:Application>
 

 For more information, see "Filtering an XMLListCollection using Regular Expressions" at FlexExamples.com.

Report abuse

Related recipes