Creating a custom ComboBox item renderer in Flex

by Peter deHaan on September 25, 2007

in ComboBox

The following example shows how you can create a simple ComboBox item renderer which displays multiline items in the ComboBox control’s drop down menu.

Full code after the jump.

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/25/creating-a-custom-combobox-item-renderer-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="top"
        backgroundColor="white">

    <mx:XMLList id="statesXMLList">
        <state abbrev="AL" name="Alabama" />
        <state abbrev="AK" name="Alaska" />
        <state abbrev="AZ" name="Arizona" />
        <state abbrev="AR" name="Arkansas" />
        <state abbrev="CA" name="California" />
        <state abbrev="CO" name="Colorado" />
        <state abbrev="CT" name="Connecticut" />
    </mx:XMLList>

    <mx:ComboBox id="comboBox"
            prompt="Please select a State..."
            dataProvider="{statesXMLList}"
            rowCount="3"
            labelField="@name"
            itemRenderer="ComboBoxItemRenderer" />

</mx:Application>

View ComboBoxItemRenderer.mxml

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/25/creating-a-custom-combobox-item-renderer-in-flex/ -->
<mx:VBox xmlns:mx="http://www.adobe.com/2006/mxml"
        styleName="plain">

    <mx:Label text="{data.@name}"
            fontSize="11"
            fontWeight="bold" />
    <mx:Label text="{data.@abbrev}"
            fontSize="9"
            paddingLeft="10" />

</mx:VBox>

View source is enabled in the following example.

{ 22 comments… read them below or add one }

1 flex_sd September 26, 2007 at 10:30 am

peterd,

i’m designing custom combo box to auto open on mouseover and auto close on mouse out (i.e. without mouse selection). i’d like to also remove the down arrow entirely.

please post an example.

in my attempts, mouseOver=”combobox.open()” opens the drop down list on mouseover. no problems there.

however mouseOut=”combobox.close()” is triggered when the mouse leaves the combo box (fine) and when the mouse pointer moved into the drop down list (bugger!).

playing with itemRollOver/Out gets trick.

thought i’d challenge you here :^)

Thanks for the blog, it’s very useful.

Reply

2 Dan November 6, 2007 at 7:27 pm

Can someone suggest how to make an “editable” combobox? simply adding editable=true – only changes the display behavior, how does one return then new value?

Reply

3 Javier Julio February 20, 2008 at 1:30 pm

Dan, you get the new value by working with the “value” property of the comboBox.

Reply

4 Brent April 2, 2008 at 11:49 am

Thanks a ton! Exactly what I was looking for!

Reply

5 Tolga October 6, 2008 at 11:32 am

Hi Peter,

i’ve a problem with the selectedItem property of the combobox when using an array as dataProvider.

I got a dataGrid listing from httpService, e4x format xml.

sample xml is:

<root>
 <row>
  <domain>batidental.com.tr</domain>
  <description/>
  <alias>21</alias>
  <maxalias>100</maxalias>
  <mailbox>0</mailbox>
  <maxmailbox>100</maxmailbox>
  <quota>100</quota>
  <transport>virtual</transport>
  <backupmx>NO</backupmx>
  <modified>2008-09-20 11:19:19</modified>
  <active>YES</active>
 </row>
 <row>
  ..
 </row>
</root>

I want to automatically select combobox item via the datagrid selectedItem addressing.

<mx:ComboBox id="ed_fTransport" editable="false"
    dataProvider="['virtual','local','relay']"
    selectedItem="{domainList.selectedItem.transport}"/>

<!-- for testing -->
<mx:Text id="testBox" text="{domainList.selectedItem.transport}" />

In this case, dataGrid selectedItem property for transport value retuns an <mx_internal_uid> together with actual value like:

<transport>
  virtual
  <mx_internal_uid>7B709DAD-E0F2-FB4C-4ACA-D3600DBF8C3B</mx_internal_uid>
</transport>

Looked in bug db however could not find any solution yet. I could use xmllist or fire up a function in actionscript, but this way it is easy to code, especially if you have lot’s of similar form elements in an app.

Thanks.

Reply

6 KC January 2, 2009 at 9:41 pm

Does any one know how to extend the length of the ComboBox dropdown menu? I would like to see all the options on first click, instead of needing a scrollbar.
Any ideas?

Reply

7 Peter deHaan January 3, 2009 at 12:21 am

KC,

Try setting the rowCount property on the ComboBox object to the length of the data provider.

Peter

Reply

8 Anonymous January 30, 2009 at 10:54 pm

did anybody try flex2? its more easy and not very complicated

Reply

9 mary August 13, 2009 at 2:51 pm

excellent. Is there a way to output text when a state is selected? I would like give a brief description about the types of flowers for that particular state

thanks

Reply

10 Peter deHaan August 13, 2009 at 4:37 pm

@mary,

Yeah, there are a few ways, but this should work as a starting point:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="top"
        backgroundColor="white">
 
    <mx:Script>
        <![CDATA[
            private function comboBox_labelFunc(item:XML):String {
                return item.@name + " (" + item.@abbrev + ")";
            }
        ]]>
    </mx:Script>
 
    <mx:XMLList id="statesXMLList">
        <state abbrev="AL" name="Alabama" desc="Yeah, we got some flowers. Some pretty nice ones." />
        <state abbrev="AK" name="Alaska" desc="Not many flowers here. Mostly too cold. But we have snow." />
        <state abbrev="AZ" name="Arizona" desc="Mostly prickly flowers here. And scorpions." />
        <state abbrev="AR" name="Arkansas" desc="I assume we have some flowers." />
        <state abbrev="CA" name="California" desc="Lots of flowers." />
        <state abbrev="CO" name="Colorado" desc="Yep, flowers here too." />
        <state abbrev="CT" name="Connecticut" desc="Probably. I don't know geography or flowers." />
    </mx:XMLList>
 
    <mx:ComboBox id="comboBox"
            prompt="Please select a State..."
            dataProvider="{statesXMLList}"
            labelFunction="comboBox_labelFunc" />
 
    <mx:Text id="txt"
            text="{comboBox.selectedItem.@desc}"
            width="{comboBox.width}" />
 
</mx:Application>

Peter

Reply

11 mary August 15, 2009 at 1:21 pm

Thank you very much. Your description on flowers was hilarious – it made my day.

I am having some troubles with the text, I have added wordwrap=true but still it doesnt come out correct. Is there a way to insert a break so that I can make sure it goes to the next line?

Reply

12 Peter deHaan August 15, 2009 at 5:48 pm

@mary,

If you want an explicit line break, add a “\n” in the text. Or make sure that your <mx:Text/> control sets the width property so it will wrap when the text reaches a certain width.

Peter

Reply

13 Sharat October 8, 2009 at 12:13 pm

Hi,

First of all, thanks for the code. I have ended up using this in my application. One thing I want to know is how do you select a value by default? Say, I have to select California by default. I haven’t found a way to do it yet. Please let me know.

Thanks,
Sharat

Reply

14 Peter deHaan October 8, 2009 at 12:30 pm

@Sharat,

The easiest way would be to set the selectedIndex property to 4.

Peter

Reply

15 Sharat October 8, 2009 at 12:34 pm

Peter,

Thanks for the quick response. Yes, that would be the easiest but is there a way to do it based on value? In my application, I get the text, say “California” and the index might not be consistent all the time.

Thanks,
Sharat

16 Sharat October 8, 2009 at 12:37 pm

I tried doing selectedItem = “text” and it doesn’t seem to work.

17 Peter deHaan October 8, 2009 at 12:40 pm

@Sharat,

Check out this article by Adobe’s Alex Harui; “SelectedItem and ComboBox”.

Peter

18 Sharat October 8, 2009 at 12:47 pm

Peter,

Thanks a lot. This is exactly what I was looking for.

Sharat

19 Peter deHaan October 8, 2009 at 12:52 pm

Or, if you just wanted the easy solution, try the following example which uses E4X to quickly parse the states XML by state name to find the match (so you can set the selectedItem property):

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/09/25/creating-a-custom-combobox-item-renderer-in-flex/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="top"
        backgroundColor="white">
 
    <mx:Script>
        <![CDATA[
            protected function selectStateByName(stateName:String):void {
                var states:XMLList = statesXMLList.(@name == stateName);
                if (states.length() > 0) {
                    comboBox.selectedItem = states[0];
                } else {
                    comboBox.selectedIndex = -1;
                }
            }
        ]]>
    </mx:Script>
 
    <mx:XMLList id="statesXMLList">
        <state abbrev="AL" name="Alabama" />
        <state abbrev="AK" name="Alaska" />
        <state abbrev="AZ" name="Arizona" />
        <state abbrev="AR" name="Arkansas" />
        <state abbrev="CA" name="California" />
        <state abbrev="CO" name="Colorado" />
        <state abbrev="CT" name="Connecticut" />
    </mx:XMLList>
 
    <mx:ApplicationControlBar dock="true">
        <mx:Button label="Select California"
                themeColor="haloGreen"
                click="selectStateByName('California');" />
        <mx:Button label="Select Oregon"
                themeColor="red"
                click="selectStateByName('Oregon');" />
    </mx:ApplicationControlBar>
 
    <mx:ComboBox id="comboBox"
            prompt="Please select a State..."
            dataProvider="{statesXMLList}"
            rowCount="3"
            labelField="@name"
            itemRenderer="ComboBoxItemRenderer" />
 
</mx:Application>

You’ll notice that the California button selects the correct state, whereas the Oregon button resets the selectedIndex property to -1, since no matches were found in the XML. Also note that I haven’t tested the code very thoroughly. I don’t know how it would handle multiple states named “California” in the data provider, and I also never tested this in a initialize or creationComplete handler to see if it correctly selects a state by default.

Peter

20 Sharat October 8, 2009 at 3:08 pm

Peter,

Thanks again! Works like a charm. I dont care about the other handlers and the code does everything I need.

Thanks,
Sharat

21 ATD December 8, 2009 at 1:56 am

Hi,

I tried to adapt this example to Flex 4, but haven’t been able to get it working.

Reply

22 juanabreu January 7, 2010 at 9:24 pm

thank you for the awesome post i have a really easy question for someone of your caliber. i ahve more then a couple of columns on my datagrid and i would like to test for the length of the strings and when the string is greated then night i would like to make then red. when i try one column i have no problem as soon as i expand to more then one column i run into trouble can you please help me.

 if (parseFloat(data.col1.length) != 9){
        (setStyle("color", (parseFloat(data.col1.length) != 9) ? NEGATIVE_COLOR : POSITIVE_COLOR))
    }
	if (parseFloat(data.col2.length) > 15){
	(setStyle("color", (parseFloat(data.col2.length) > 15) ? NEGATIVE_COLOR : POSITIVE_COLOR))
    }
		//:setStyle("color", (parseFloat(data.col2.length) > 15) ? NEGATIVE_COLOR : POSITIVE_COLOR);
    }
    }

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: