One of the things I like most about ColdFusion’s tag is the SELECTED attribute, give it a value and it figures out which one to pre-select. The Flex ComboBox allows you to set selectedIndex (the relative element position) but not selectedValue. Actually, ComboBox does have a selectedValue property, but that is used to read the value of the selected item, and can’t be used to set the value of the item to be selected.
Coincidentally, while I was working on this, both Scott Stroz and Ray Camden posted solutions to the exact same problem. Scott’s solution involved calling a method to set the value, and I really think that the selectedValue property should be used to be consistent with how ComboBox itself works. Ray’s solution allows for a property to be set (he defined a new property for this), but his solution would not work for me as my dataProvider was being populated after the control had been created (it is being populated by a call to a CFC).
So, here is my solution. It’s bit more complex than what Scott and Ray suggested, but it does support selectedValue, it’ll also allow that property to be changed as needed (even after control creation), and it also properly handles delayed dataProvider population.
Here is the code:




And here is a simple test case:




57 thoughts

  1. Ben – quick question. You mentioned that the dataProvider was being populated by a call to a CFC. If you set selectedValue before the dataprovider is populated with data from the CFC, I assume the correct value will still be selected. How is this happening? Is commitProperties called when the dataProvider is populated with data?

  2. Ben, maybe I’m missing the point here, but ComboBox (and a few others like List and DataGrid ) not only offers the selectedIndex property to select an item by using a numeric index but also a selectedItem property which selects an item from the dataProvider by passing in a reference.

  3. Lifesaver! I had written some really convoluted, long-winded function to set my selectedIndex property. This is great. Thanks again..

  4. Thanks Ben! I’m new to flex, with a background in vb/access then java/swing then c#, and I expected combobox to do this out of the box, but your code works beautifully and gives me a look into how to extend components as well!

  5. Ben,
    I noticed in your example you used an Array with static data to set the combo box values. Would it be possible to show an example using mx:WebService?

  6. Ben – thank you so much for this – i just saved a bunch of time trying to figure out how to set that selectedIndex. Just wanted you to know that this is working and we thank you!

  7. this is my solution:
    public function initCombobox(obj:Object):void{
    for(var i:int=0;i<obj.dataProvider.length;i++){
    var selected:String = obj.dataProvider[i].selected;
    if(selected != null){
    if(selected == "true"){
    obj.selectedIndex = i;
    break;
    }
    }
    }
    }
    <area>
    <item label="??" data="-1" />
    <item label="??" data="0570" />
    <item selected="true" label="??" data="0571" />
    <item label="??" data="0572" />
    <item label="??" data="0573" />
    <item label="??" data="0574" />
    <item label="??" data="0575" />
    <item label="??" data="0576" />
    <item label="??" data="0577" />
    <item label="??" data="0578" />
    <item label="??" data="0579" />
    <item label="??" data="0580" />
    </area>

  8. <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml&quot; layout="absolute">
    <mx:Script>
    <![CDATA[
    public function initCombobox(obj:Object):void{
    for(var i:int=0;i<obj.dataProvider.length;i++){
    var selected:String = obj.dataProvider[i].selected;
    if(selected != null){
    if(selected == "true"){
    obj.selectedIndex = i;
    break;
    }
    }
    }
    }
    ]]>
    </mx:Script>
    <mx:ArrayCollection id="ac">
    <mx:Array>
    <mx:Object label="A" data="1"/>
    <mx:Object label="B" data="2"/>
    <mx:Object label="C" data="3"/>
    <mx:Object label="D" data="4"/>
    <mx:Object label="E" data="5" selected="true"/>
    <mx:Object label="F" data="1"/>
    <mx:Object label="G" data="1"/>
    </mx:Array>
    </mx:ArrayCollection>
    <mx:ComboBox id="testComb" dataProvider="{ac}" x="37" y="64"></mx:ComboBox>
    <mx:ComboBox id="testComb2" dataProvider="{ac}" creationComplete="initCombobox(testComb2)" x="37" y="94"></mx:ComboBox>
    </mx:Application>

  9. Ben Forta you rock! I’m new to Flex and been having some adjustments coming from a pure Cold Fusion background. I was surprised to find the orginal Flex Combobox without a direct selectvalue property. I spent too much time trying to figure this out. I’m so glad you write this custom component….life saver.

  10. A great help – the only thing I added was setting selectedIndex=-1 before the search – otherwise, if the data is not found it will show whatever the previously selected value was. This can happen when used with a database which has some incorrect or empty values, and if it shows the previous value it is not obvious there is a problem. With -1, the CB is blank, making it clear.

  11. Thanks to wujian’s post I was finally able to overcome this frustrating obstacle. However being a coldfusion /.net developer, it seems to me that this is something that should be built into the component. I’m just learning flex/as3 and finding I’m writing volumes of code to do the simplest mundane things. This is what makes ASP.NET so popular, the controls do all the heavy lifting and much of this grunt coding is built into the controls themselves. Flex is supposed to be an RIA langueage remember. Ben please pass my frustions and opinions on to the flex team. I DONT WANT TO WRITE CODE THAT SHOULD BE BUILT INTO A COMPONENT!
    Just my 2 cents. I feel better now. 🙂

  12. Ben (or anyone, for that matter!), not sure if this thread is still monitored or not but I have a question:
    I have duplicated this control – THANKS – by extending mx:List. Because this list is necessarily several thousand items long (everyone in our firm), I have added the following to the logic in order to show the highlighted dp item:

    this.selectedIndex = i;
    //added:
    this.verticalScrollPosition = i;

    It works great, except for the first time that it’s called – the correct item is selected, but the verticalScrollPosition doesn’t take effect. If you scroll down the list you can see that the correct item is selected – it just doesn’t scroll down to that position. I’m assuming this is because the parent component hasn’t been completely rendered yet (this is a Cairngorm app where selectedValue property is bound to a property of a value object in the modelLocator), but the creationComplete event is dispatched before the selectedValue setter is called so I’m at a loss. Each subsequent view of that screen correctly scrolls to the item in the list.
    Any advice on how to force this to scroll on the first call?
    Thanks in advance,
    Joe

  13. (flex newbie here)
    thanks for this… but how do i ‘bind’ the selected index to a datagrid selection?
    ie, something like, ideally:
    <comp:ComboBox2 x="112" y="39" dataProvider="{rstClients}" selectedValue="<b>{surveyGrid.selectedItem.SCLIENTNAME}</b>" labelField="SCLIENTNAME" width="205" />
    compared to textinput controls’ bindings, triggering combobox updates through datagrid’s itemfocusin seems ‘dirty’.

  14. I have slight twist on this, I have cfselect that gets its data from a cfdirectory tag. The cfselect provides the user with a list of xml file in a directory. After the user selects an xml file I need to read the values in the xml file and put them into text boxes on the flash form.
    I can get everything but cannot get the value of the selectedItem from the cfselect combo box.
    Any suggestions here as I know nothign about flex
    Thanks
    Jim

  15. thanks Elton – Because of real estate limitations, I ended up switching back to the data aware combo box class.
    In theory these should be pretty darned identical in behavior, but I think what might have gotten it to work was setting the creationPolicy="all" attribute on the application.
    Not sure whether this was definitely the fix, but it sure did seem to help with a lot of other little gotcha’s throughout the application and eliminated a bunch of null checking, etc.
    Just thought I would add this note to the thread incase it helps someone else.

  16. I tried the this.scrollToIndex(i); It doesn’t scroll to the right position and my datagrid shows empty rows when I scroll up and down with the mouse. And then they will appear after a while. Any suggestions?
    Jaqueline

  17. Hi,
    Another newbie to Flex here..
    I’m trying to Bind this to a selectedItem from a DataGrid to a Combo box please can someone tell me if this is possible with this Combobox as Flex does no support SelectedItem..
    I see you can use a static value in the SelectedValue and it works fine, but if you put a Dynamic Value in ie. selectedValue="{datagrid.selectedItem.column}" it doesn’t seem to work..
    Any adive would be great..
    Matt

  18. Thank you. I had the same problem of the dataprovider not being populated at the time of the control creation. This is a very clean implementation.

  19. I too am grateful to you Ben for posting this solution. I spent no less than 10 hours f’ing with a stupid ComboBox trying to get it to do something I could EASILY do in HTML, JSP, or JSF years ago! It’s utterly amazing that Adobe has not provided an OOB solution for this common scenario.
    I’m new to Flex and recently committed to using it to develop a large portion of my small startup company’s product, but this ComboBox nonsense is making me wonder if I made the right choice. How many more wasted days will I experience chasing solutions to problems that should be part of the OOB product.
    Thanks again Ben!
    Tom

  20. Hi Ben,
    Thanks for this great extension to the ComboBox! Thanks mostly for commenting the code because I was having so much trouble getting this thing to work. It turned out I was setting the dataProvider with databinding, BEFORE I populated the dataProvider.
    Making the call to set dataProvider right after populating my label data object did the trick. I’m planning on always using this ComboBox.
    Question, why doesn’t the Flex framework already define a selectedValue method for mx:ComboBox in the first place, does it have anything to do with data binding?
    thanks,
    Derek

  21. Thanks so much. I was fortunate enough to do a quick search before I wasted too much time trying to find the "selectedValue" property. This has been a great help, and it is very much appreciated!

  22. Tristan, great work! 🙂 This is what I really wanted!
    Let’s hope that Adobe will add this into Flex 3 …. it’s really not to have this very basic functionality in a combobox!
    thnx

  23. Great post! My previous – less elegant solution was to use a helper function to convert the item to an index…
    public function findItemIndex( dp:IList, data:String ):int
    {
    for( var i:int = 0; i < dp.length; ++i )
    {
    if( dp.getItemAt(i).data == data )
    return i;
    }
    return -1;
    }
    &lt;mx:ComboBox dataProvider="{myDP}" selectedIndex="{findItemIndex(myDP, selectedItem) }" /&gt;

  24. Thanks Ben! This is amazing.
    In case anyone wants to make their comboBox default to the size of the DataProvider (it defaults to a drop down of only a few items and you have to scroll to the rest) then you can add code like this:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:ComboBox xmlns:mx="http://www.adobe.com/2006/mxml&quot;
    rowCount="{myDataProvider.length}">

  25. Don’t forget that if the dataprovider is coming from a webservice to change
    var item:String = this.dataProvider[i].data; to
    var item:String = this.dataProvider[i].DATA;
    🙂

  26. thanks is one word because coming from HTML, Java to flex this was eye opening that built in combobox has no simple properties like this..
    flex is open source that doesn’t mean Adobe should leave to developer but basic properties are their responsibility. Anyways new comers like us face more problems because other part of world has all methods for doing simple work like selecting index where value = ?

  27. If your dataprovider is ever updated the selectedValue will be lost and the comboBox will reset itself to the first value in the list. You can fix this by changing the set dataProvider function and adding bSelectedValueSet = true as follows:
    if (o!=null && o.length)
    {
    // Got it, set flag
    bDataProviderSet = true;
    bSelectedValueSet = true;
    }

  28. Thanks so much for this post – it is still relevant! I am dealing with a Cairngorm application and have a header in one view, using this comboBox component. I have changed the selectedValue parameter to equal {modelLocator.workflowSate}.
    I have another view with the navigation that has tree component that offers a secondary option to change the workflowState. I am missing a step though, because if I click on a node in the tree, the view successfully changes, but the comboBox in the header view does not "automagically" adjust.
    How can I set the comboBox view to "listen" to see if the workflowSate has changed, and adjust accordingly? If it is too much to explain in the comments, if anyone could forward me to a relevant post, I would be very grateful! TIA!

  29. Ben, thx for posting this. It works great. I was creating a new property on my object called "propIndex" and dynamically setting it when my "prop" property was being set by a setter. However, even though the propIndex was bindable, and the data was changing, the combobox didn’t change. I switched to your combobox and set selectedValue = {prop} and it works great. THX!!

  30. You could also override the combobox and create that method inside of it:
    package flex.components.util {
    import mx.collections.IList;
    import mx.controls.ComboBox;
    public class ComboBoxExt extends ComboBox {
    public function findItemIndex(data:String):int {
    var list:IList = IList(this.dataProvider);
    for (var i:int = 0; i<list.length; ++i) {
    if (list.getItemAt(i).data == data) return i;
    }
    return -1;
    }
    }
    }
    And you can call something like this in your script section
    myView.myCombo.selectedIndex = myView.myCombo.findItemIndex("somedata");
    Hope this sheds another light 😉

  31. I dont get it. Im using this component NEXT to a datagrid. I select a row in the datagrid and the ComboBox changes how I want it to. But now I want to be able to change the combobox and sent that to a server but I can only seem to get the index. I want the label and data. when I use code hinting, It shows me that I can now use the slectedValue but it causes an error. How do I see all the values assosiated with the combo box, Label, Data?

  32. In my flex app, I have 2 datagrids and when the app opens both datagrids get populated with data, dg2 visibilty is set to false; dg1 visibility is set to true. When the user clicks on a row in dg1, it populates combo boxes with that row data. That all works according your suggestion above (Thx!). I have a button, when clicked, it makes visible dg2. When I click on the button, dg2 becomes visible but then I want to be able to populate the same combo boxes with the row data in dg2. However, I’ve tried it and nothing gets selected in the combo boxes. any suggestions or examples? I’m using flex 3. Any help is appreciated.

  33. In my flex app, I have 2 datagrids and when the app opens both datagrids get populated with data, dg2 visibilty is set to false; dg1 visibility is set to true. When the user clicks on a row in dg1, it populates combo boxes with that row data. That all works according your suggestion above (Thx!). I have a button, when clicked, it makes visible dg2. When I click on the button, dg2 becomes visible but then I want to be able to populate the same combo boxes with the row data in dg2. However, I’ve tried it and nothing gets selected in the combo boxes. any suggestions or examples? I’m using flex 3. Any help is appreciated.

  34. Hi, Thanks your example, And I made a little change of yours, I think it will be more convenient
    override protected function commitProperties():void
    {
    // invoke ComboBox version
    super.commitProperties();
    // If value set and have dataProvider
    if (bSelectedValueSet && bDataProviderSet)
    {
    // Set flag to false so code won’t be called until selectedValue is set again
    bSelectedValueSet=false;
    // Loop through dataProvider
    for (var i:int=0;i<this.dataProvider.length;i++)
    {
    // Get this item’s data
    var item:String = this.dataProvider[i][this.data]; //The little change
    // Check if is selectedValue
    if(item == _selectedValue)
    {
    // Yes, set selectedIndex
    this.selectedIndex = i;
    break;
    }
    }
    }
    }
    In this way , Our value field name of our dataprovider can not be data but the other name.
    thank you.

  35. Thanks a lot….
    For Xml list
    =============================================
    <?xml version="1.0"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml&quot; xmlns:ns2="myComponents.*">
    <mx:Script>
    <![CDATA[
    import mx.managers.PopUpManager;
    import mx.core.IFlexDisplayObject;
    private var helpWindow:IFlexDisplayObject;
    private var books:XML = <books>
    <book publisher="Addison-Wesley" name="Design Patterns" ids="0"/>
    <book publisher="Addison-Wesley" name="The Pragmatic Programmer" ids="1"/>
    <book publisher="Addison-Wesley" name="Test Driven Development" ids="2"/>
    <book publisher="Addison-Wesley" name="Refactoring to Patterns" ids="3"/>
    <book publisher="O’Reilly Media" name="The Cathedral & the Bazaar" ids="4"/>
    <book publisher="O’Reilly Media" name="Unit Test Frameworks" ids="5"/>
    </books>;
    private function his():void {
    xselect.selectedValue = "5";
    }
    ]]>
    </mx:Script>
    <ns2:xmlcmbbox id="xselect" dataProvider="{books.book}" labelField="@name" />
    <mx:Button click="his();" label="hiss"/>
    </mx:Application>
    =============================================================
    <?xml version="1.0" encoding="utf-8"?>
    <mx:ComboBox xmlns:mx="http://www.adobe.com/2006/mxml"&gt;
    <mx:Script>
    <![CDATA[
    private var _selectedValue:String;
    private var bSelectedValueSet:Boolean = false;
    private var bDataProviderSet:Boolean = false;
    // Override committ, this may be called repeatedly
    override protected function commitProperties():void {
    // invoke ComboBox version
    super.commitProperties();
    // If value set and have dataProvider
    if (bSelectedValueSet && bDataProviderSet) {
    // Set flag to false so code won’t be called until selectedValue is set again
    bSelectedValueSet=false;
    // Loop through dataProvider
    for (var i:int=0;i<this.dataProvider.length;i++){
    // Get this item’s data
    var item:String = this.dataProvider[i].@ids;
    // Check if is selectedValue
    if(item == _selectedValue) {
    // Yes, set selectedIndex
    this.selectedIndex = i;
    break;
    }
    }
    }
    }
    // Trap dataProvider being set
    override public function set dataProvider(o:Object):void {
    // invoke ComboBox version
    super.dataProvider = o;
    // This may get called before dataProvider is set, so make sure not null and has entries
    if (o!=null && o.length) {
    // Got it, set flag
    bDataProviderSet = true;
    }
    }
    // set for selectedValue
    public function set selectedValue(s:String):void {
    // Set flag
    bSelectedValueSet = true;
    // Save value
    _selectedValue = s;
    // Invalidate to force commit
    invalidateProperties();
    }
    ]]>
    </mx:Script>
    </mx:ComboBox>
    ============================================================

  36. Why would I get always get [object Object] when I switch from the regular combobox to this one? I am using a webservice connected to a CFC.

  37. Very close to what I want to do.
    This solution works until you set the combobox to be editable.
    What I am trying to has three indexes in the combobox (-1, 0, and one that the user can type in a value). Using your solution I can make the combobox value aware, but as soon as I flag the combobox as editable it will no longer lets me submit a value.
    Does anyone have a work around for that?

Leave a Reply