Using a CheckBox to filter items in a DataGrid in Flex

by Peter deHaan on March 12, 2008

in ArrayCollection, DataGrid

The following example shows how you can filter items in a Flex DataGrid using a CheckBox control, and the ArrayCollection class’s filterFunction property.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2008/03/12/using-a-combobox-to-filter-items-in-a-datagrid-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:Script>
        <![CDATA[
            import mx.controls.dataGridClasses.DataGridColumn;

            private function toggleFilter():void {
                if (checkBox.selected) {
                    arrColl.filterFunction = processFilter;
                } else {
                    arrColl.filterFunction = null;
                }
                arrColl.refresh();
            }

            private function processFilter(item:Object):Boolean {
                return parseFloat(item.value) == 0;
            }

            private function value_labelFunc(item:Object, col:DataGridColumn):String {
                return item[col.dataField].toFixed(2);
            }
        ]]>
    </mx:Script>

    <mx:ArrayCollection id="arrColl">
        <mx:source>
            <mx:Array>
                <mx:Object name="ColdFusion" value="0.00" />
                <mx:Object name="Dreamweaver" value="0.12" />
                <mx:Object name="Fireworks" value="1.01" />
                <mx:Object name="Flash" value="0" />
                <mx:Object name="Flash Player" value="-0.00" />
                <mx:Object name="Flex" value="0.00" />
                <mx:Object name="Illustrator" value="2.92" />
                <mx:Object name="Lightroom" value="0.32" />
                <mx:Object name="Photoshop" value="0.06" />
            </mx:Array>
        </mx:source>
    </mx:ArrayCollection>

    <mx:Panel status="{arrColl.length}/{arrColl.source.length} item(s)">
        <mx:DataGrid id="dataGrid"
                dataProvider="{arrColl}"
                verticalScrollPolicy="on">
            <mx:columns>
                <mx:DataGridColumn dataField="name" />
                <mx:DataGridColumn dataField="value"
                        labelFunction="value_labelFunc" />
            </mx:columns>
        </mx:DataGrid>
        <mx:ControlBar>
            <mx:CheckBox id="checkBox"
                    label="Filter DataGrid"
                    click="toggleFilter();" />
        </mx:ControlBar>
    </mx:Panel>

</mx:Application>

View source is enabled in the following example.

{ 20 comments… read them below or add one }

1 Michael Matti March 12, 2008 at 8:15 pm

Looks like there’s a typo in the title: “using a combobox to filter items…” when, of course, it’s a checkbox in the code and example.

Great site, by the way. I’ve been learning a lot from these posts … much appreciated.

Reply

2 peterd March 12, 2008 at 8:18 pm

Michael Matti,

Rats! Thanks for the heads up. I changed the article title, but left the URL the same, so it doesn’t break any links or whatever.

Peter

Reply

3 minidxer March 13, 2008 at 3:02 am

Thanks your great article.I have translated some contents on flexexamples.com to Chinese on my blog ( http://blog.minidx.com) , in order to be more friendly and easy for chinese users to read. All the translated files contain the original URL and be credited by Peter deHaan. Hope could get your approve.

Reply

4 peterd March 13, 2008 at 8:09 am

minidxer,

That’s great, thanks!
Yep, everything on the blog is creative commons, so you’re free to use/translate the content as long as you attribute the work and add a link back to this site.

Thanks,
Peter

Reply

5 Arnold May 14, 2008 at 1:36 pm

Hi Peter,

I’m currently doing a filter function in an application. My understanding is that when you try to filter a specific dataField you can do this: “if (item.origin == “WA”)” “origin” is a specific column on a datagrid column. But what if I want to store that datafield column in a variable?

for example: var custom_datafield:String = “origin” ;
and do this: if (item.custom_datafield == “WA”) — I am not getting any returned records and it did not give me errors as well. I need your expertise on this.
Are there any other way to do this?

In case you are wondering why I need to store the dataField name into a variable is because I am creating a datagrid component that will accept any XML file using only one datagrid and one filter functionality.

Thanks,
Arnold

Reply

6 Prashanth Samanth June 9, 2008 at 4:19 am

Hi Peter,

According to my Project, I need to show some more Filters based on the ComboBox Selection,

First One

For Example: If User selects the 1st option in the Combo, I need to show few more Option in the Bottom, and if the again selects the other option in the ComboBox, I need to show Different filter based on Selection.

and second point, Based on the selection of the Filter I need to update the Report by the Update Button.

Hope Atleast I will get the First Criteria

Thanks a lot

Reply

7 Theo van der Sluijs August 1, 2008 at 1:50 am

Wow, this is great… but….. it would be nice to filter on multiple items.
;-)

Reply

8 Stefan Bistram January 14, 2009 at 2:28 pm

Hi Peter,

thanks a lot for all the great examples.

I’ve created a DataGrid with filtering via a text input field:
http://blog.sbistram.de/2009/01/14/flex-enhanced-search-flex3-datagrid/
Maybe someone has usage for it.

Cheers,
Stefan

Reply

9 Steve February 3, 2009 at 5:22 am

Is there any way we can filter multiple items via checkbox?

Reply

10 yuy0 February 5, 2009 at 12:27 am

hye…

i want to ask u;what if i have multiple checkbox??user can click on multiple checkbox to filter the datagrid.can u show me how the code look like??

thanks in advance!!

Reply

11 Dimiorla February 22, 2009 at 9:15 am

Great site,
I’ve been learning a lot from these posts
But i kan’t find a posts on combobox DataGrid filter
any tips

Reply

12 FlexGuy March 2, 2009 at 10:23 am

I’ve been using many of your articles to aid in my flex development. Cudos to you for your posts. Keep them coming!

Reply

13 Kurt April 7, 2009 at 2:17 pm

what about using a combo box to filter? I tried to set one up, but it only repeats the first item that I want filtered it doesn’t check the rest of the XML file.

Reply

14 Michael April 12, 2009 at 9:32 am

Good example. I’m using a XMLListCollection and have filtering working. However I want to add the same type of label you have for the panel status: {arrColl.length}/{arrColl.source.length}. My XMLListCollection is called tixXML and I can get the displayed size (tixXML.length) however how do I get the length of the unfiltered tixXML? After I filter the results tixXML.length changes to the number of displayed results however I also want the length of the unfiltered results? Do I need to set a var to the original amount or is there a property I can access?

Thanks in advance.

Reply

15 Javier May 7, 2009 at 8:07 pm

Stefan Bistram and site admin:

Great examples, i needed something to search a data grid, but filtering the ArrayCollection resulted in a much more elegant solution.

Thanks

Reply

16 Iwo Banas July 1, 2009 at 6:43 am

Hi,

I am working on open source, reusable extension of Flex 3 DataGrid to enable client-side filtering and searching. My solution includes filters using multiple CheckBoxes, TextInput, Slider and more…
You can find it at
http://www.iwobanas.com/2009/06/datagrid-with-client-side-filtering-and-searching/

I am looking forward any comments and suggestions from you!

Cheers,
Iwo Banaś

Reply

17 Javier Gomez September 2, 2009 at 4:52 am

Hello please someone help me with this code.

http://promotora.idataweb.com/google/final/index2.html

I need to filter the List with the checkboxes.

Thanks.

Reply

18 Peter deHaan September 2, 2009 at 8:15 am

@Javier Gomez,

Try something like this:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" color="#000000"
                fontWeight="bold" width="100%" height="100%" alpha="1.0" backgroundGradientAlphas="[1.0, 1.0]"
                backgroundGradientColors="[#FFFFFF, #FFFFFF]"
                initialize="proyects.send();">
 
    <mx:Script>
        <![CDATA[
            import mx.controls.Alert;
 
            private function toggleCategory(type:String):void {
                xmlListColl.refresh();
            }
 
            private function xmlListColl_filterFunc(item:Object):Boolean {
                if ((item.@type == "restaurant") && restaurantCh.selected) {
                    return true;
                }
                if ((item.@type == "bar") && barCh.selected) {
                    return true;
                }
                if ((item.@type == "disco") && discoCh.selected) {
                    return true;
                }
                return false;
            }
        ]]>
    </mx:Script>
 
    <mx:XMLListCollection id="xmlListColl" source="{proyects.lastResult.marker}" filterFunction="xmlListColl_filterFunc" />
 
    <mx:HTTPService id="proyects" url="markersall.xml" resultFormat="e4x" />
 
    <mx:Panel width="220" height="136" layout="absolute" title="Tipo de proyectos" cornerRadius="10" right="10" top="40" borderColor="#FF7225" backgroundColor="#FFC34E" alpha="1.0" borderAlpha="100">
        <mx:CheckBox id="restaurantCh" x="10" y="10" label="Proyectos en venta" fillAlphas="[1.0, 1.0, 1.0, 1.0]" fillColors="[#F27CE6, #FF00FF, #FF00FF, #FF00FF]"
                     selected="true" change="toggleCategory('restaurant');" borderColor="#000000"/>
        <mx:CheckBox id="barCh" x="10" y="36" label="Proyectos en desarrollo" fillAlphas="[1.0, 1.0, 1.0, 1.0]" fillColors="[#A6ACFF, #A6ACFF]"
                     selected="true" change="toggleCategory('bar');" borderColor="#000000"/>
        <mx:CheckBox id="discoCh" x="10" y="62" label="Proyectos terminados" fillAlphas="[1.0, 1.0, 1.0, 1.0]" fillColors="[#927474, #927474, #927474, #927474]"
                     selected="true" change="toggleCategory('disco');" borderColor="#000000"/>
    </mx:Panel>
    <mx:Panel width="220" layout="absolute" title="Proyectos" cornerRadius="10" right="10" borderColor="#FF7225" bottom="20" top="185" borderAlpha="100">
        <mx:List x="-0.05" y="0.1" dataProvider="{xmlListColl}" enabled="true" labelField="@name" width="199.6" height="100%" backgroundColor="#FFC34E" borderThickness="0" themeColor="#CACACA" id="proyectlist" />
    </mx:Panel>
 
</mx:Application>

Peter

Reply

19 Flex Blog November 17, 2009 at 10:32 am

This is a great example. If you are looking for a way filter an ArrayCollection using an TextInput please visit my weblog.

Reply

20 Flexicious December 5, 2009 at 2:45 pm

If you need a custom component that does all of the nitty gritty of datagrid filter, pager, footer, and sort, please look at http://www.flexicious.com or http://www.flexdatagrid.com...

Reply

Leave a Comment

Sorry, this blog is terrible at eating HTML comments.
If you're pasting any HTML/XML/MXML code, you need to convert your < characters to &lt; and your > characters to &gt; .

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Anti-Spam Protection by WP-SpamFree

Previous post:

Next post: