Filtering an XMLListCollection using the filterFunction property and regular expressions
Here is another handy little tip that you see all over the web, how do I filter a data grid (or other list-based control) based on a user’s input? Or more specificially, how to I limit the items that show in a list based on what a user types.
Since I already created a simple XML document of Countries/States, I thought I’d create a basic form that lets a user type in the first few characters of a state name and have the DataGrid filter its results. You’ll also notice that I had to do some not-so-tricky E4X filtering to extract only the American state names.
Full code after the jump.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white">
<mx:Script>
<![CDATA[
private function filterFunc(item:Object):Boolean {
return item.text().match(new RegExp("^" + stateName.text, "i"));
}
]]>
</mx:Script>
<mx:XML id="dp" source="countries_states.xml" format="e4x" />
<mx:XMLListCollection id="xmlListColl" source="{dp.country.(@name == 'United States of America').state}" filterFunction="filterFunc" />
<mx:VBox>
<mx:HBox width="100%">
<mx:Label text="Name:" />
<mx:TextInput id="stateName" width="100%" change="xmlListColl.refresh()" />
</mx:HBox>
<mx:DataGrid id="dataGrid" dataProvider="{xmlListColl}">
<mx:columns>
<mx:DataGridColumn id="codeCol" dataField="@code" headerText="Abbr:" width="60" />
<mx:DataGridColumn id="nameCol" dataField="*" headerText="Name:" width="240" />
</mx:columns>
</mx:DataGrid>
<mx:Label text="Filtered: Showing {xmlListColl.length} record(s)" visible="{stateName.text.length > 0}" />
</mx:VBox>
</mx:Application>
View source is enabled in the following example.
Peter deHaan
Peter deHaan currently works for Adobe on the Flex SDK QA team. While not working on Flex, Flash, and ColdFusion applications, Peter enjoys making up bios and writing in 3rd person. Peter's rarely updated blog can be found at blogs.adobe.com/pdehaan/, actionscriptexamples.com, airexamples.com, and coldfusionexamples.com.
-
Add Widgets (Content Sidebar)
This is your Content Sidebar. Edit this content that appears here in the widgets panel by adding or removing widgets in the Content Sidebar area.
20 Responses to Filtering an XMLListCollection using the filterFunction property and regular expressions
Leave a Reply Cancel reply
-
Categories
- Accordion
- AccordionHeader
- ActionScript
- AddChild
- AdvancedDataGrid
- Alert
- alpha
- Animate
- AnimateProperties
- Application
- Application (Spark)
- ArrayCollection
- BarChart
- baseColor
- beta
- beta1
- beta2
- Bitmap
- Bitmap/BitmapData
- BitmapData
- BitmapFill
- BitmapFill (Spark)
- BitmapGraphic
- BitmapImage
- BitmapImage (Spark)
- BitmapImageResizeMode
- Border (Spark)
- BorderContainer (Spark)
- Box
- BuildInfo
- Button
- Button (Spark)
- ButtonBar
- ButtonBar (Spark)
- ByteArray
- Camera
- Charting
- CheckBox
- CheckBox (Spark)
- ClassFactory
- CollectionEvent
- Color
- ColorPicker
- ColorUtil
- ComboBox
- ComboBoxArrowSkin
- Compiler
- Component
- Component (Spark)
- Configuration
- Container
- ContextMenu
- ContextMenuEvent
- ContextMenuItem
- CSSCondition
- CSSSelector
- CSSStyleDeclaration
- CurrencyFormatter
- CursorManager
- Data Binding
- DataGrid
- DataGrid (Spark)
- DataGridColumn
- Date
- DateBase
- DateChooser
- DateField
- DateFormatter
- Debugging
- DefaultComplexItemRenderer
- DefaultTileListEffect
- DropDownList
- DropDownList (Spark)
- DropDownListButtonSkin
- DropDownListSkin
- DropShadowFilter
- E4X
- Effects
- Ellipse
- EmailValidator
- Embed
- Event
- Fade
- FileFilter
- FileReference
- fill
- Filters
- Flash
- Flash Integration
- FlashVars
- Flex 3 SDK
- Flex Builder
- Flex Builder 3
- Flex SDK
- Flex4
- FLVPlayback
- FocusManager
- FontLookup
- Fonts
- Form
- Form (Spark)
- FormHeading (Spark)
- FormItem
- FormItem (Spark)
- Forms
- FTETextField (Spark)
- FullScreen
- FullScreenEvent
- FxAnimateColor
- FxButtonBar
- FxCheckBox
- FXG
- FxHScrollBar
- FxHSlider
- FxList
- FxNumericStepper
- FxRadioButton
- FxRotate3D
- FxScroller
- FxTextArea
- FxTextInput
- FxToggleButton
- FxVScrollBar
- FxVSlider
- getStyleDeclaration()
- GradientEntry
- Graphic (Spark)
- HBox
- HDividedBox
- HGroup (Spark)
- HorizontalLayout
- HorizontalList
- HSBColor (Spark)
- HScrollBar (Spark)
- HSlider
- HSlider (Spark)
- HTML template
- ID3Info
- Image
- Image (Spark)
- ImageSnapshot
- itemRenderer
- JointStyle
- Label
- Label (Spark)
- Legend
- LegendItem
- LigatureLevel
- Line
- LinearGradientStroke
- LineScaleMode
- LinkBar
- LinkButton
- List
- List (Spark)
- Menu
- MenuBar
- Metadata
- MetadataEvent
- Model
- Mouse
- MouseCursor
- MouseEvent
- Move
- Namespace
- NavigatorContent (Spark)
- needsSWF
- NetConnection
- NetStream
- Nightly Builds
- NumberBaseRoundType
- NumberFormatter
- NumberValidator
- NumericCompare
- NumericStepper
- NumericStepper (Spark)
- ObjectProxy
- ObjectUtil
- paddingLeft
- paddingRight
- Panel
- Panel (Spark)
- Parallel
- Path
- PieChart
- PieSeries
- PieSeriesItem
- PopUpAnchor (Spark)
- PopUpButton
- PopUpManager
- ProgrammaticSkin
- ProgressBar
- PropertyChangeEvent
- QName
- RadialGradient
- RadioButton
- RadioButton (Spark)
- RadioButtonGroup
- RadioButtonGroup (Spark)
- Rect
- RegExp
- Regular Expressions
- Repeater
- RichEditableText
- RichText
- RichText (Spark)
- RichTextEditor
- Rotate
- Rotate3D (Spark)
- Scroller (Spark)
- Sequence
- setStyle()
- SimpleText
- SimpleText (Spark)
- skinClass
- Slider
- SliderEvent
- SolidColor
- SolidColorStroke
- Sort
- SortField
- Sound
- SoundEffect
- Spinner (Spark)
- SpriteVisualElement (Spark)
- StageDisplayState
- States
- StringUtil
- StringValidator
- StyleManager
- Styles
- SWFLoader
- SWFObject
- System
- SystemManager
- TabBar
- TabBar (Spark)
- TabNavigator
- TabStopFormat
- Text
- Text Layout Framework (TLF)
- TextArea
- TextArea (Spark)
- TextBox
- TextConverter
- TextEvent
- TextFlow
- TextFlowUtil
- TextFormat
- TextGraphic
- TextInput
- TextInput (Spark)
- TextLayoutFormat
- TextView
- Themes
- TileLayout
- TileList
- TileOrientation
- Timer
- TitleWindow
- TitleWindow (Spark)
- TLF
- ToggleButton (Spark)
- ToggleButtonBar
- ToolTip
- Transition
- Tree
- TruncationOptions
- UIComponent
- UIFTETextField
- Updater
- URLLoader
- URLRequest
- URLUtil
- URLVariables
- ValidationResultEvent
- Validator
- Validators
- VBox
- VDividedBox
- Vector
- VerticalLayout
- VerticalLayout (Spark)
- VGroup (Spark)
- Video
- VideoDisplay
- VideoElement
- VideoElement (Spark)
- VideoEvent
- VideoPlayer (Spark)
- VideoPlayerScrubBar
- ViewStack
- VScrollBar (Spark)
- VSlider
- VSlider (Spark)
- XML
- XMLList
- XMLListCollection
- ZipCodeValidator
- ZipCodeValidatorDomainType
- Zoom
-
Articles
- December 2010
- November 2010
- October 2010
- September 2010
- August 2010
- July 2010
- June 2010
- May 2010
- April 2010
- March 2010
- February 2010
- January 2010
- December 2009
- November 2009
- October 2009
- September 2009
- August 2009
- July 2009
- June 2009
- May 2009
- April 2009
- March 2009
- February 2009
- January 2009
- December 2008
- November 2008
- October 2008
- September 2008
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
-
Meta


I did a similar example on my site http://etc.joshspoon.com. But I didn’t do the refresh (change=”xmlListColl.refresh()” )as easily as you did, though there is more then one way to skin a Flex app.
Keep up the great examples!
The written filter function in this example has a serious limitation – it only filters items from top level of hierarchy in XMLListCollection
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
If you want to use a variable to specify which column you want to filter on, use [].
E.g.
return item[filterField] == cbFilterL1Select.text;
where filterField is string in which you store the column name.
Thanks,
Istvan
Is the fact that only the top level of hierarchy in the XMLListCollection is filtered using filterFunction a bug?
Like JabbyPanda said that is a HUGE limitation. Is there somework around for this? Is there a way to assign a filterFunction on each level of the XMLListCollection hierarchy?
Ug! how could I do this in flex 2 its driving me crazy
Seconding Frogmo’s request for a workaround to the filterFunction’s deficient filtering. I think they just used ListCollections on flat hierarchies and when they added the XML counterpart, they forgot expand the filterFunction’s functionality.
FrogMo / peterh,
Can one of you file a bug/enhancement request at http://bugs.adobe.com/flex/ so Adobe can track the issue? Also, if you post the bug number here, I’m sure a few people can vote on the issue.
Thanks,
Peter
Has a bug report been filed for the top level filtering problem? I haven’t been able to find any information on it.
RObert,
Can you please file a bug on the top level filtering problem at http://bugs.adobe.com/flex/ and include a simple test case, if possible.
Thanks,
Peter
Done. Bug ID SDK-17808. https://bugs.adobe.com/jira/browse/SDK-17808
Voted and subscribed.
Thanks,
Peter
Great tip!!!! It helped me a LOT!
Thanx!
Elvis Fernandes
From one Peter to another, thanks. However, I keep getting an error, “TypeError: Error #1006: value is not a function.” I’m not sure why this pops up. I originally tried applying this code to a working filterFunction that matched characters exactly, but when that didn’t work, I recreated an app from scratch, following the example above, but I still get the “…not a function” error. Any clues why this would show up?
Peter,
Which version of the Flex SDK are you using?
I just tried on 3.4 and didn’t have any errors.
Peter
Thanks!
Veeeeery helpful:)
Hey Peter,
You are just superb…………you don’t know how much you help me in every ways in flex development by posting so many working examples. They are very much self -explainatory and useful for everyone. Thanks a ton buddy…………….May god bless you all the happiness in the world…
Cheers…
Hi Peter,
I’m new in Flex development and trying to find some examples where Data grid ( or Advance data grid ) can be filtered based on Start date and End date selection . I could not able to find something related on your sit e. Can you please provide sample example .
Thanks,
Rishi
@Rishi,
I haven’t tested the code very much, but this may help get you started; http://blog.flexexamples.com/2010/02/01/filtering-an-mx-datagrid-control-by-date-range-using-flex/
Peter
Hi Peter, I’m having the same problem as the “other Peter”, I’m getting this error:
TypeError: Error #1006: value is not a function.It is dispatched as soon as my HTTPService returns succesfull and executes this code:
xmlList.source = result.children()Which dispatches internally in the following order:
at mx.collections::XMLListCollection/set source() >
at mx.collections::ListCollectionView/set list() >
at mx.collections::ListCollectionView/http://www.adobe.com/2006/flex/mx/internal::reset() >
at mx.collections::ListCollectionView/internalRefresh() >
at views.bkmgr::AddResourcesView/equipFilterFunc()
The filter function is exactly:
private function equipFilterFunc(item:Object):Boolean
{
return item.text().match(new RegExp("^" + txtin_searchFilter.text, "i"));
}
I’m running FB 4.5.1, thanks in advance!