Creating a custom ComboBox item renderer in Flex

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.

26 thoughts on “Creating a custom ComboBox item renderer in Flex

  1. 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.

    1. Man I love you !!!
      Uv solved my problem…gave me xactly what i wanted….u rock genie !!!
      Thanks a lot !! Just helped me out of would-be crisis.
      God bless u.

  2. 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?

  3. 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.

  4. 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?

  5. 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

    1. @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

  6. 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?

    1. @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

  7. 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

      1. 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

      2. 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

      3. Peter,

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

        Thanks,
        Sharat

  8. 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);
        }
        }
  9. Is there a way to maintain the two lines of text once an item has been selected. I need to display two lines of text in the closed state. Is this possible in Flex 3?

  10. Hi,

    I am trying to add duplicate data into combobox. for example if i want to add “” 2 times. I am finding difficult to select them. One of them won’t display at all, istead i can see a blank space in that place. How to solve this problem.

    Need Help

    Thanks
    kiran

  11. i need your help immediately. i’m trying to add items to the combo box directly from a data base. i’m successfully connect to database and get the relevant data but i can’t add them in to the combo box if u can help it’ll be lot to me.
    thanks

Comments are closed.