Photo credits: Matt Steen

To see more recent blog posts please visit http://www.sanative.net/blog


Flex Comboboxes: Psuedo OPTGROUP (grouping of options)

UPDATED 12/18/07
I added an example and the source by request. You can view the source here

I spent a bit of time researching the combobox component in Flex because I needed the ability to visually group my select lists. I discovered that Flex did not utilize a mechanism for <optgroup> like HTML does.

After a bit of research I decided to use an itemRenderer and "fake it" The top level categories are never used, only the children, so they are only there for reference. What I ended up doing was creating a custom component that visually styled the items based upon the data. The parent nodes have a data value of 0, since the data field is not used for those nodes. Here is an example:

<?xml version="1.0" encoding="utf-8"?>
<mx:Label xmlns:mx="http://www.adobe.com/2006/mxml"
    text="{data.@label}"
    toolTip="{data.@label}"
    fontWeight="{myFontWeight}"
    paddingLeft="{myLeftPadding}"
    dataChange="changeStyles()">

    <mx:Script>
        <![CDATA[
       
            [Bindable]
            private var myFontWeight:String = "normal";
           
            [Bindable]
            private var myLeftPadding:int = 0;
           
            private function changeStyles():void  {
                if(data.@data == 0) {
                    myFontWeight = "bold";
                    myLeftPadding = 0;
                } else {
                    myFontWeight = "normal";
                    myLeftPadding = 15;
                }
            }
        ]]>
    </mx:Script>
</mx:Label>

This component is called in my Flex application like this. Comp:FilterCombo is another custom component I use, but can be replaced with a combobox

<comp:FilterCombo id="selectFilter1" itemRenderer="components.FilterComboRenderer" labelField="@label" valueField="@data" width="250" height="22"/>

And here is your end result!

Let me know if you have a better way of doing this. I'd love to see Flex have an optgroup capability for selects, I think this is something folks run into frequently.

Comments
BlogCFC 5.8.001 © Ray Camden