Creating two related ComboBoxes

This is a semi-common problem. You have two (or more) ComboBox controls and you want the options in second combo box to change based on the selected item in the first combo box. Or in a real world case, you have a list of countries and a list of provinces/states/regions in that country. When the user changes the value in the country combo box to “Canada”, you would only want to display a list of Canadian provinces/territories in the second combo box. Although if the user selected USA in the country combo box, you would only want to show the American states/regions.

Anyways, enough jibber-jabber, lets see this in action.

Full code after the jump.

Download source (ZIP, 2K) | View MXML | View countries_states.xml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle" backgroundColor="white">

    <mx:XML id="dp" source="countries_states.xml" format="e4x" />

    <mx:Form>
        <mx:FormItem label="Country:">
            <mx:ComboBox id="countryCB" dataProvider="{dp.country}" labelField="@name" />
        </mx:FormItem>
        <mx:FormItem label="State:">
            <mx:ComboBox id="stateCB" dataProvider="{countryCB.selectedItem.state}" />
        </mx:FormItem>
    </mx:Form>

</mx:Application>

View source is enabled in the following example.

A reader asked how you could convert this to use three related CheckBox controls instead of two. The following example shows how you can create three related check boxes to show Country, State, and City:

View MXML

<?xml version="1.0" encoding="utf-8"?>
<!-- http://blog.flexexamples.com/2007/08/04/creating-two-related-comboboxes/ -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
        layout="vertical"
        verticalAlign="middle"
        backgroundColor="white">

    <mx:XML id="dp" source="countries_states_cities.xml" format="e4x" />

    <mx:Form>
        <mx:FormItem label="Country:">
            <mx:ComboBox id="countryCB"
                    dataProvider="{dp.country}"
                    labelField="@name" />
        </mx:FormItem>
        <mx:FormItem label="State:">
            <mx:ComboBox id="stateCB"
                    dataProvider="{countryCB.selectedItem.state}"
                    labelField="@name" />
        </mx:FormItem>
        <mx:FormItem label="City:">
            <mx:ComboBox id="cityCB"
                    dataProvider="{stateCB.selectedItem.city}"
                    labelField="@name" />
        </mx:FormItem>
    </mx:Form>

</mx:Application>

I also modified the XML format slightly from the previous example to make it work with multiple levels:

countries_states_cities.xml

<?xml version="1.0" encoding="utf-8"?>
<countries>
    <country name="Canada">
        <state code="AB" name="Alberta">
            <city name="Calgary" />
            <city name="Edmonton" />
        </state>
        <state code="BC" name="British Columbia">
            <city name="Nanaimo" />
            <city name="Vancouver" />
            <city name="Victoria" />
        </state>
        <state code="ON" name="Ontario">
            <city name="Ottawa" />
            <city name="Toronto" />
        </state>
        <state code="QC" name="Quebec">
            <city name="Montreal" />
        </state>
        <state code="SK" name="Saskatchewan">
            <city name="Moosejaw" />
        </state>
    </country>

    <country name="United States of America">
        <state code="AZ" name="Arizona">
            <city name="Phoenix" />
        </state>
        <state code="CA" name="California">
            <city name="Oakland" />
            <city name="Los Angeles" />
            <city name="Sacramento" />
        </state>
        <state code="CO" name="Colorado">
            <city name="Denver" />
        </state>
        <state code="DC" name="District of Columbia">
            <city name="Washington" />
        </state>
        <state code="FL" name="Florida">
            <city name="Miami" />
            <city name="Orlando" />
        </state>
        <state code="GA" name="Georgia">
            <city name="Atlanta" />
        </state>
        <state code="IL" name="Illinois">
            <city name="Chicago" />
        </state>
        <state code="IN" name="Indiana">
            <city name="Indianapolis" />
        </state>
        <state code="LA" name="Louisiana">
            <city name="New Orleans" />
        </state>
        <state code="MA" name="Massachusetts">
            <city name="Boston" />
        </state>
        <state code="MI" name="Michigan">
            <city name="Detroit" />
        </state>
        <state code="MN" name="Minnesota">
            <city name="Minneapolis" />
        </state>
        <state code="NC" name="North Carolina">
            <city name="Charlotte" />
        </state>
        <state code="NJ" name="New Jersey">
            <city name="East Rutherford" />
        </state>
        <state code="NY" name="New York">
            <city name="New York" />
        </state>
        <state code="OH" name="Ohio">
            <city name="Cleveland" />
        </state>
        <state code="OR" name="Oregon">
            <city name="Portland" />
        </state>
        <state code="PA" name="Pennsylvania">
            <city name="Philadelphia" />
        </state>
        <state code="TN" name="Tennessee">
            <city name="Memphis" />
        </state>
        <state code="TX" name="Texas">
            <city name="Dallas" />
            <city name="Houston" />
            <city name="San Antonio" />
        </state>
        <state code="UT" name="Utah">
            <city name="Salt Lake City" />
        </state>
        <state code="WA" name="Washington">
            <city name="Seattle" />
        </state>
        <state code="WI" name="Wisconsin">
            <city name="Milwaukee" />
        </state>
    </country>
</countries>

View source is enabled in the following example.

55 thoughts on “Creating two related ComboBoxes

  1. Hi great examples. I was wondering how that wouuld work pulling the data from a database

    I have this but it only pulls one name:

    Also How do I display a label field and pull values from another field. Ex display dept name but the key is from deptID

    Thanks

  2. This is a very good Example,

    Could you help me,

    I want same Example but with VB , please?
    :)

  3. Hello,

    Very interesting examples.

    In the first example, i try to have the name of the state selected, i do :
    <mx:Text text=”{stateCB.selectedItem}”/>

    My question is how to have the “code” of the state selected.

    Thanks.

  4. Nice example.

    My problem is a bit different. I’m using the Adobe AutoComplete ComboBox to filter through a long list of names, so if I type “Sm” the box will pre-populate with Smecker, Smib, Smith, Smith and Smith. Is there any way to show the 2nd filtering element within the same combo box? In other words, to filter by TWO labelFields at the same time, so my results would read:

    Smecker, Joe
    Smib, Bob
    Smith, Al
    Smith, Jack
    Smith, Peter

    Thanks!

  5. Never mind – all you have to do is set the labelFunction property like so:

    Dang, that was easy!

  6. Great tutorial (actually, all of your are…this is the third of yours that I’ve mashed together for an application I’m using and so far, apart from a few little changes here and there to make it relevant to my XML schemas, everything has worked brilliantly)!

    However, I’ve got a question for you…for the first ComboBox, I’ve got XML file of fabric types that has the name, id and link to its related XML file as shown below:

    <fabric>
    	<type name="Woven Crypton" url="woven_crypton.xml" id="woven_crypton" />
    	<type name="Crypton" url="crypton.xml" id="crypton" />
    	<type name="Vinyl" url="vinyl.xml" id="vinyl" />
    </fabric>
    

    And I’ve got the following code for the second ComboBox:

    dataProvider="{fabricCB.selectedItem.@url}" labelField="@name"
    

    And that shows “woven_crypton.xml” or whatever the other values are depending on which of the three is selected.

    But what I WANT to happen is to have that second ComboBox load with the contents of that XML file which is a list of all the pattern types within that Fabric type. I’m assuming some sort of function is going to be required to grab the correct data that will be created on the fly when one of the fabric types is chosen.

    I have this working in HTML using Spry. It works amazingly, actually (the Flex solution I’m working on is phase 2 and 3 of this project), but I can’t seem to transition it all over to Flex easily.

    Any hints or suggestions?

    Thanks and thanks again for such an awesome, helpful and informative blog!

  7. kyle,

    Sorry for the slow reply. Off the top of my head, I can think of two possible solutions.

    1) You could use the HTTPService tag to load the contents of the three XML files in at runtime:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"&gt;
    
        <mx:Script>
            <![CDATA[
                import mx.events.ListEvent;
    
                private function comboBox1_change(evt:ListEvent):void {
                    httpService.url = comboBox1.selectedItem.@url;
                    httpService.send();
                }
            ]]>
        </mx:Script>
    
        <mx:XML id="dp1">
            <fabric>
                <type name="Woven Crypton"
                        url="woven_crypton.xml"
                        id="woven_crypton" />
                <type name="Crypton"
                        url="crypton.xml"
                        id="crypton" />
                <type name="Vinyl"
                        url="vinyl.xml"
                        id="vinyl" />
            </fabric>
        </mx:XML>
    
        <mx:HTTPService id="httpService" resultFormat="e4x" />
    
        <mx:ComboBox id="comboBox1"
                dataProvider="{dp1.type}"
                labelField="@name"
                prompt="Please select a fabric"
                change="comboBox1_change(event);" />
    
        <mx:ComboBox id="comboBox2"
                dataProvider="{httpService.lastResult.product}"
                labelField="@name"
                prompt="Please select a product" />
    
    </mx:Application>
    

    2) You can embed the three XML files into your Flex application at compile time using the <mx:XML /> tag and then use a switch statement in the first ComboBox control’s change handler based on the selected item:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"&gt;
    
        <mx:Script>
            <![CDATA[
                import mx.events.ListEvent;
    
                private function comboBox1_change(evt:ListEvent):void {
                    var str:String = comboBox1.selectedItem.@id;
                    switch (str) {
                        case "woven_crypton":
                            comboBox2.dataProvider = woven_crypton_xml.product;
                            break;
                        case "crypton":
                            comboBox2.dataProvider = crypton_xml.product;
                            break;
                        case "vinyl":
                            comboBox2.dataProvider = vinyl_xml.product;
                            break;
                        default:
                            comboBox2.dataProvider = [];
                            break;
                    }
                }
            ]]>
        </mx:Script>
    
        <mx:XML id="dp1">
            <fabric>
                <type name="Woven Crypton"
                        url="woven_crypton.xml"
                        id="woven_crypton" />
                <type name="Crypton"
                        url="crypton.xml"
                        id="crypton" />
                <type name="Vinyl"
                        url="vinyl.xml"
                        id="vinyl" />
            </fabric>
        </mx:XML>
    
        <mx:XML id="woven_crypton_xml" source="woven_crypton.xml" />
        <mx:XML id="crypton_xml" source="crypton.xml" />
        <mx:XML id="vinyl_xml" source="vinyl.xml" />
    
        <mx:ComboBox id="comboBox1"
                dataProvider="{dp1.type}"
                labelField="@name"
                prompt="Please select a fabric"
                change="comboBox1_change(event);" />
    
        <mx:ComboBox id="comboBox2"
                labelField="@name"
                prompt="Please select a product" />
    
    </mx:Application>
    

    Hope that helps,

    Peter

  8. Actually, I guess a third way (there are probably a bunch of other ways as well, these may not be the “best”, just the first things that came to mind).

    3) Use data binding to bind the HTTPService URL from the first ComboBox control’s selected item’s @url attribute (which means virtually no ActionScript — apart from the inline httpService.send() in the ComboBox control’s change event handler):

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"&gt;
    
        <mx:XML id="dp1" source="fabric.xml" />
    
        <mx:HTTPService id="httpService"
                url="{comboBox1.selectedItem.@url}"
                resultFormat="e4x" />
    
        <mx:ComboBox id="comboBox1"
                dataProvider="{dp1.type}"
                labelField="@name"
                prompt="Please select a fabric"
                change="httpService.send();" />
    
        <mx:ComboBox id="comboBox2"
                dataProvider="{httpService.lastResult.product}"
                labelField="@name"
                prompt="Please select a product" />
    
    </mx:Application>
    

    Peter

  9. Peter,

    Thank you so much! The third example is EXACTLY the sort of thing I was looking for. I really appreciate your help and I’m sort of embarrassed it was that easy and I didn’t even think of it. The ComboBoxes are working perfectly now and I just need to get the XML files associated with the files in the second ComboBox to populate the TileList with the correct images (which was already happening before so I don’t have much concern about getting that to work again).

    Don’t even worry about the “slow reply.” It wasn’t slow at all. I really appreciate you taking time to even help out.

    Thanks again!
    Kyle

  10. Hello Peter,

    I’m trying to implement what kyle was doing, but I keep getting errors -

    [RPC Fault faultString="A URL must be specified with useProxy set to false." faultCode="Client.URLRequired" faultDetail="null"]
    at mx.rpc.http::HTTPService/send()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\http\HTTPService.as:736]

    After extensive googling I have not found the answer and figured i’d post in hopes you could help.

    My XML is laid out as follows:

    vinstall.xml

    <?xml version="1.0"?>
    <doorOptions>
    	<doorSize>
    		<name>"6 feet"</name>
    		<url>"6.xml"</url>
    	</doorSize>
    	<doorSize>
    		<name>12 Feet</name>
    		<url>12.xml</url>
    	</doorSize>
    	<doorSize>
    		<name>30 Feet</name>
    		<url>30.xml</url>
    	</doorSize>
    </doorOptions>
    

    6.xml

    <?xml version="1.0"?>
    <products>
    	<item>
    		<name>Item1</name>
    		<pic>6/items/item1.jpg</pic>
    	</item>
    	<item>
    		<name>Item 2</name>
    		<pic>6/items/item2.jpg</pic>
    	</item>
    </products>
    <floors>
    	<floor>
    		<name>floor1</name>
    		<pic>6/floors/floor1.jpg</pic>
    	</floor>
    	<floor>
    		<name>floor2</name>
    		<pic>6/floors/floor2.jpg</pic>
    	</floor>
    </floors>
    

    *same apples to 12.xml and 30.xml

    my MXML

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
    
    
    <mx:XML id="dp1" source="vinstall.xml">
    
    </mx:XML>
    
    <mx:HTTPService id="httpService" resultFormat="e4x" url="{comboDoor.selectedItem.@url}"/>
    
    	<mx:ComboBox x="141" y="36" id="comboDoor"
    		dataProvider="{dp1.doorSize}"
    		labelField="name"
    		prompt="Select Door"
    		change="httpService.send();" />
    
    	<mx:ComboBox x="351" y="36" id="comboProd"
    		dataProvider="{httpService.lastResult.item}"
    		labelField="name"
    		prompt="Product" />
    
    	<mx:Image x="0" y="113" source="{comboProd.selectedItem.pic}" width="850" height="615"/>
    
    </mx:Application>
    

    I’ve been bashing my head all day trying to figure out what I’m doing wrong. I’ve also tried your other 2 examples that you posted for kyle to no avail.

    help? :)

    thanks

  11. Hey Kastro…just out of curiosity, have you tried removing the quotes from inside your element tags? That could be causing an issue when the value is being harvested.

    Just a thought…

  12. Yea I tried that too, but it keeps giving me that proxy error.

    I’ve tried running it right from the developing directory (ie: /users/kastro/etc etc) and via http://localhost/flex/etc etc

    Tried it on OSX and Win32 with both returning the same results. I know it has to be something small that I’m missing..

    Could you either post your mxml/xml that is working for you? or shoot me an email?

    fwatlington at tycoint .com

    :)

    Will check back later.. and thanks for the reply kyle..

  13. Hmmm…I didn’t look all that closely at your code last night, Kastro, but if I had to guess, it’s something to do with this error you’re receiving:

    [RPC Fault faultString="A URL must be specified with useProxy set to false." faultCode="Client.URLRequired" faultDetail="null"]
    at mx.rpc.http::HTTPService/send()[E:\dev\3.0.x\frameworks\projects\rpc\src\mx\rpc\http\HTTPService.as:736]

    It would seem as though you’re trying to send data via a different domain to the application (or rather, you’re trying to access it from a different domain) and as Flex/Flash are client-side technologies, that’s a HUGE no-no. Same thing applies to cross-domain JavaScript stuff. Due to security risks, it’s generally not possible…unless you use a proxy server or a server-side technology.

    I did a quick Googling and this backed up what I thought:
    http://www.mail-archive.com/flexcoders@yahoogroups.com/msg10234.html

    If that ISN’T the case, I’d be more than happy to send you my working example. :)

  14. Going to take a look @ link and see what I can do. But its all running locally.. :/

    http://localhost:8888/flex/vinstall/

    and what its trying to access when the combobox is selected is

    http://localhost:8888/flex/vinstall/6.xml

    *port is default for XAMPP

    so its not going to another domain… Same applies when I try to run it from the dev dir

    file://c:/flex/vinstall/

    It does load the vinstall.xml from the beginning, just has the issues when it tries to load the 6.xml (minus the quotes in the name tag now) which is in the same dir..

    C:\flex\vinstall\vinstall.xml
    C:\flex\vinstall\6.xml

    & for the HTTP

    C:\xampp\htdocs\flex\vinstall\vinstall.xml
    C:\xampp\htdocs\flex\vinstall\6.xml

    I’d like to take a look at your working example as then I can manipulate it and see what is different from what I have..

    The countries/states example that this page is about works fine when I run it on both the http:// and via file://

    Again I appreciate you helping me Kyle..

  15. That’s weird. :(

    I’m sending you an email right now from my Gmail account. It’s got the whole application + all the associated images, so it’s about a 7MB zip. Sorry about the huge size. It was just easier to lump it all together than try to weed out the stuff that isn’t necessary.

    Hopefully you can get something working!

    Oh, and it’s the fabric_httpservice.mxml file. I forgot I had a number of versions with various functionality in there.

  16. Kastro,

    Sorry for the slow reply. I had a few minutes to look at this today and saw two errors:
    1) The binding is incorrect in your HTTPService tag. The HTTPService tag’s url property should use comboDoor.selectedItem.url (node) and NOT comboDoor.selectedItem.@url (attribute):

    <mx:HTTPService id="httpService"
            resultFormat="e4x"
            url="{comboDoor.selectedItem.url}"/>
    

    2) The following XML (from your 6.xml example above) is not valid:

    <?xml version="1.0"?>
    <products>
        <item>
            <name>Item1</name>
            <pic>6/items/item1.jpg</pic>
        </item>
        <item>
            <name>Item 2</name>
            <pic>6/items/item2.jpg</pic>
        </item>
    </products>
    <floors>
        <floor>
            <name>floor1</name>
            <pic>6/floors/floor1.jpg</pic>
        </floor>
        <floor>
            <name>floor2</name>
            <pic>6/floors/floor2.jpg</pic>
        </floor>
    </floors>
    

    The XML document has two root nodes <products /> and <floors />. You either need to remove the <floors /> node (or <products /> node) or wrap them in a new root node. Something like <root><products /><floors /></root>

    Hope that helps,
    Peter

  17. ahhhhhhhh… The reason I had the was because I wanted the user to be able to select from a group of floors that only pertain to the 6ft gallery. They can choose any product from the 6ft gallery, and choose any floor from 6ft gallery.. Like a mix/match..

    *going to go play!

    Thanks both of you!

    (if you know of how i can apply my mxml/xml based on the above scenario feel free to let me know :) but I dont want to be greedy w/ your generosity..

  18. Hi

    In my current project, I want to achieve the same result but with different approach. I have 3 combobox, say Combo1, Combo2, Combo3. The values of Combo2 depends on selected value of Combo1, and values of Combo3 depends on selected value of Combo2. The values of all these 3 combobox should be populated through flash remoting (calling aspx files — diff combobox will call diff aspx file) instead of creating an XML upfront. The aspx files will return an XML file(on the fly) to Flex . Here is how I call the aspx file for my Combo1:

    <dropdown:XMLComboBox x=”176″ y=”26″ width=”160″ id=”Combo1″ xmlFile=”http://localhost/prbiclass/listCombo1.aspx” change=”changeEvt(event)” />

    This part works fine. I manage to get the list of values for Combo1. The problem starts here:

    1. How do I pass the selected value of Combo1 to listCombo2.aspx in the changeEvt function? By right the url should look like this http://localhost/prbiclass/listCombo2.aspx?parameter=selectedValueOfCombo1

    2. Assuming I manage to call the aspx in the ChangeEvt function, how do I bind the XML data into Combo2.

    3. Is this efficient? coz there would be lots of remote calls.. Is there a better way to do it?

    Thanks for your help.

  19. Hi
    Code is very usefull.
    Can you help me in how to get the selected data in combo box to a label.

  20. venkat krishna,

    Try using the ComboBox control’s selectedItem property. It should give you the currently selected item in the data provider.

    Something like the following:

    <mx:Label text="{myComboBox.selectedItem.url}" />
    

    Peter

  21. Hey Guys this is exactly what I was looking for – ( sorry if I seem a bit slow here ) although the source has no flash file – how would I incorporate this into my flash movie? I am using Flash 8

    Thank you

  22. Frank,

    You wouldn’t really use this in Flash 8 (or CS3/CS4, for that matter). The examples on this blog are only for the Adobe Flex SDK (versions 3+ specifically).

    In Flash 8, you’d need to rewrite this using ActionScript 2.0 and use event handlers on the ComboBox controls to determine when the first one changes so you can manually set the data provider in the second ComboBox control. A good place to start would be to ask on the FlashCoders mailing list.

    Peter

  23. I like your pure coding, very nice
    I have another one for you : 2 related comboboxes, a form for the detail and that all related to a tree

    project owner
    project name
    project status1
    project status2

    with of course multiple owners, each have on or more projects, and each of the projects has one or more status (details) the status1 is in fact the title
    en plus each project status has one or more images
    If you like i can mail you the site for wich i wrote it
    sincerely yours
    fréderic, Belgium

  24. Hi everyone,
    I have a request to make,
    Initially there should be only one label (Choose your country) & comboBox. On selecting the country the remaining labels & corresponding comboxes should be populated dynamically, III’ly when he/she chooses state its corresponding city has to be populated…
    The catch here is that in the xml i receive,its like this, not all countries have the same number of required fields for the address, for ex: After choosing CANADA, the application should show 3 labels namely
    label “Province/Territory” & comboBox containing all the provinces
    label “City/Ville/Community” & comboBox containing all the cities for the selectes province,& which has to got dynamically after choosing the province.
    label “Postal code” & comboBox containing the postal code of the selected city.
    & all these above data are got from xml(both text for the label & data for comboBox).

    But if i choose INDIA, then it should show 4 labels instead of 3 for CANADA as the following,
    label “State” comboBox & containing all the states
    label “City/District” & comboBox containing all the cities for the selected state
    label “Locality” & comboBox containing the localities for the selected city
    label “Zipcode” & a textfield containing the zipcode for the selected locality.
    remember the flex application gets to know the number of labels & comboBoxes and their names & dataproviders all from the different xmls only
    THANKING ANYONE WHO IS WILLING TO HELP ME…

  25. Hi Peter,

    Using the information that you have provided above, I have created a ComboBox that populates a TileList based on said combobox’s selected item. The selectedItem of the ComboBox can be any of the following categories: All, Her Shirts, Her Sweaters, Her Intimates, Her Bottoms. The default selectedItem is All which should be populating pictures and labels of all of the inventory items in my xml file. However, I cannot get the TileList to populate the pictures. Instead, the TileList populates with the labels only. I have tried everything that I can find on the web and cannot get my TileList to populate with pictures and labels as it should. Can you tell me what I’m doing wrong? I am a noob to Flex and this is my first application so any help I can get is HUGELY appreciated!

    My XML is laid out as follows:

    <?xml version="1.0" encoding="UTF-8"?>
    <categories>
        <category name="All Items">
            <product name="Shirt One"> 
                <pic>10254brightpinktee.jpg</pic> 
            </product>
            <product name="Shirt Two">
                <pic>8965greentee2.jpg</pic>
            </product>
            <product name="Shirt Three">
                <pic>98725pinktee3.jpg</pic>
            </product>
            <product name="Intimates One">
                <pic>k0905116panty.jpg</pic>
            </product>
            <product name="Intimates Two">
                <pic>k0905113panty.jpg</pic>
            </product>
            <product name="Bottoms One">
                <pic>810ladiesbottomchoc-f-thumb.jpg</pic>
            </product>
            <product name="Bottoms Two">
                <pic>7017ladiesbottomdhtr-f.jpg</pic>
            </product>
            <product name="Sweater One">
                <pic>875sweaterfushia-f-thumb.jpg</pic>
            </product>
            <product name="Sweater Two">
                <pic>7001sweaterblack-f-thumb.jpg</pic>
            </product>
            <product name="Bottoms Three">
                <pic>7817ladiesbottommidnight-f-thumb.jpg</pic>
            </product>
        </category>
        <category name="Her Shirts">
            <product name="Shirt One">
                <pic>10254brightpinktee.jpg</pic>
            </product>
            <product name="Shirt Two">
                <pic>8965greentee2.jpg</pic>
            </product>
            <product name="Shirt Three">
                <pic>98725pinktee3.jpg</pic>
            </product>
        </category>
        <category name="Her Intimates">
            <product name="Intimates One">
                <pic>k0905116panty.jpg</pic>
            </product>
            <product name="Intimates Two">
                <pic>k0905113panty.jpg</pic>
            </product>
        </category>
        <category name="Her Bottoms">
            <product name="Bottoms One">
                <pic>810ladiesbottomchoc-f-thumb.jpg</pic>
            </product>
            <product name="Bottoms Two">
                <pic>7017ladiesbottomdhtr-f.jpg</pic>
            </product>
            <product name="Bottoms Three">
                <pic>7817ladiesbottommidnight-f-thumb.jpg</pic>
            </product>
        </category>
        <category name="Her Sweaters">
            <product name="Sweater One">
                <pic>875sweaterfushia-f-thumb.jpg</pic>
            </product>
            <product name="Sweater Two">
                <pic>7001sweaterblack-f-thumb.jpg</pic>
            </product>
        </category>
    </categories>

    My MXML is as follows:

    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
            layout="absolute"
            horizontalAlign="center"
            verticalAlign="middle"
            applicationComplete="service.send()">
     
        <mx:XML id="dp"
                source="categories_items_pictures.xml"
                format="e4x" />
     
        <mx:HTTPService id="service"
                url="categories_items_pictures.xml"
                resultFormat="e4x"/>
     
        <mx:VBox verticalGap="0"
                width="465" height="580"
                x="290" y="5"
                backgroundColor="#000000"
                borderStyle="solid" borderColor="#000000"
                verticalScrollPolicy="off" horizontalScrollPolicy="off">
            <mx:HBox x="19" y="612"
                    width="455" height="38"
                    backgroundColor="#5E5E5E"
                    cornerRadius="5"
                    borderStyle="solid"
                    borderColor="#000000"
                    horizontalGap="20"
                    verticalAlign="middle">
                <mx:Text text="  Select a Category:               "
                        fontSize="12"
                        fontWeight="bold"
                        height="21"
                        textAlign="left"
                        color="#FFFFFF"
                        width="134"/>
                <mx:ComboBox  id="itemcategoryCB"
                        editable="false"
                        fillColors="[#FFFFFF, #000000]"
                        enabled="true"
                        height="22"
                        fillAlphas="[1.0, 1.0]"
                        themeColor="#F97AC5"
                        dataProvider="{dp.category}"
                        labelField="@name" />
            </mx:HBox>
     
            <mx:TileList id="storeinventory"
                    width="455" height="500"
                    verticalScrollPolicy="on"
                    allowMultipleSelection="false"
                    dataProvider="{itemcategoryCB.selectedItem.product}"
                    labelField="@pic"
                    columnCount="3">
                <mx:itemRenderer>
                    <mx:Component>
                        <mx:Image source="assets/thumbs/{data.@pic}"/>
                   </mx:Component>
               </mx:itemRenderer>
            </mx:TileList>
        </mx:VBox>
     
    </mx:Application >

    I don’t know if it matters, but all of my pictures are in the “src” folder of the application under “assets”. The pictures that I am attempting to load are thumbs also. Further, I wrote my XML file in Dreamweaver CS4.

    Again, any help is hugely appreciated.

    Thanks in advance! :)

    Deebs

    1. @Deebs,

      You have data.@pic, but it looks like <pic/> is a node, not an attribute.
      Try replacing the <mx:Image/> tag with a <mx:Label/> tag and display the value of {data.@pic} and see if it is a valid string/path.

      Peter

  26. Hi Peter,

    You’re right, is a node and not an attribute in my XML file.

    I tried replacing the &ltmx:Image/&gt tag with a &ltmx:Label&gt tag which displays the value of {data.pic} like so:

    &ltmx:Label text=”assets/thumbs/{data.pic}”/&gt

    It ends up retrieving the correct path and displaying the text “assets/thumbs/picturefilename” in each of the tiles contained in the TileList. However, when I change the &ltmx:Image/&gt tag back to &ltmx:Image source=”assets/thumbs/{data.@pic}”/&gt it doesn’t load any of the pictures.

    Not sure what I’ve done wrong here as the path is definitely valid and everything should be working accordingly…

    Thanks again for any help that you can offer here.

    Deebs

  27. Hi Peter,

    To clarify, when I change the tag back to &ltmx:Image source=”assets/thumbs/{data.@pic}”/&gt, the application loads the image placeholder icon in each of the tiles, however, does not load the actual pictures despite the path being valid.

    Thanks again,

    Deebs

    1. @Deebs,

      Out of curiosity, try giving a fully qualified image URL. Something like:

      <mx:Image source="http://yourdomain.com/projects/assets/thumbs/{data.@pic}" />

      That, and try just putting a plain <mx:Image source="assets/thumbs/875sweaterfushia-f-thumb.jpg" /> somewhere in the application and see if that displays correctly.

      Peter

  28. Hi Peter,

    So, I’ve got it working… kind of. Perhaps you’ll have some answers for me, because being new to Flex, I am rather confused by how I’ve got it working.

    So I tried &lt mx:Image source=”assets/thumbs/875sweaterfushia-f-thumb.jpg” /&gt and it loaded that one image and tiled it all the way across the tilelist like it was supposed to. So then, knowing that I had the functionality to load an image and that it wasn’t some issue with my version of Flex or my computer, I started messing around with the code.

    When I entered:
    &lt mx:Image source=”/Users/Dee/Documents/Learning Flex/NGC Site/NGCSiteApp/src/assets/inventory-thumbs/{data}”/ &gt

    instead of:
    &ltmx:Label text=”assets/thumbs/{data.pic}”/&gt

    The images load, but they all shrink to the size of the tilelist’s tile instead of forcing the tilelist’s tile to match their size. They do this despite the tilelist having no row height or column width value specified. When I start using my combobox to sift through the different categories of items, all of a sudden the images populate to their proper sizes (as indicated by their file sizes). However, every time a new selection is made in the combobox, the images randomly either shrink or stay the same. So, to be sure that I am explaining this correctly, I’ll choose “All” from the ComboBox. One image named Shirt One will be normal size and another image named Bottoms One will be shrunk. Then I’ll select Her Sweaters from the ComboBox and one sweater image will be shrunk while the other two sweater images are their correct sizes. I’ll choose “Her Shirts” from the ComboBox and a random number of shirts will be shrunk (sometimes all three, sometimes just one of the three). Then I’ll go back to “All” in the ComboBox and all of the items will be shrunk.

    This also worked the same way when I entered:
    &ltmx:Image source=”assets/inventory-thumbs/{data}”/&gt

    It also should be noted that sometimes when I select the “All” value from the ComboBox, only 3 of 9 items actually populate to the TileList.

    Just for clarity purposes, the below is my newest MXML code:

    &lt?xml version=”1.0″ encoding=”utf-8″?&gt
    &ltmx:VBox xmlns:mx=”http://www.adobe.com/2006/mxml”
    verticalGap=”0″ height=”580″ x=”21″ y=”623″
    backgroundColor=”#000000″
    borderStyle=”solid”
    borderColor=”#000000″
    width=”465″
    verticalScrollPolicy=”off”
    horizontalScrollPolicy=”off”&gt

    &ltmx:XML id=”dp” source=”categories_items_pictures.xml” format=”e4x” /&gt

    &ltmx:HBox x=”19″ y=”612″ width=”455″ backgroundColor=”#5E5E5E” height=”38″ cornerRadius=”5″ borderStyle=”solid” borderColor=”#000000″ horizontalGap=”20″ verticalAlign=”middle”&gt
    &ltmx:Text text=” Select a Category: ” fontSize=”12″ fontWeight=”bold” height=”21″ textAlign=”left” color=”#FFFFFF” width=”134″/&gt
    &ltmx:ComboBox id=”itemcategoryCB” editable=”false” fillColors=”[#FFFFFF, #000000]” enabled=”true” height=”22″ fillAlphas=”[1.0, 1.0]” themeColor=”#F97AC5″ dataProvider=”{dp.category}” labelField=”@name”&gt
    &lt/mx:ComboBox&gt
    &lt/mx:HBox&gt

    &ltmx:TileList id=”storeinventory” width=”455″ height=”500″ verticalScrollPolicy=”on” allowMultipleSelection=”false” dataProvider=”{itemcategoryCB.selectedItem.product.pic}” labelField=”@name” iconField=”pic” columnCount=”3″&gt
    &ltmx:itemRenderer&gt
    &ltmx:Component&gt
    &ltmx:Image source=”assets/inventory-thumbs/{data}”/&gt
    &lt/mx:Component&gt
    &lt/mx:itemRenderer&gt
    &lt/mx:TileList&gt
    &lt/mx:VBox &gt

    I don’t know if it matters, but this is a component of an application and not the application itself.

    Thanks for your time in helping me with this Peter. I didn’t think it would be such a pain in the butt!

    Deebs

  29. Oh, and I should also mention that it works the exact same way whether I specify an HTTPService tag or not…

  30. hey peter,
    First thank you very much for this useful post.
    I know this post is very old but I’ve seen a weird problem in my implementation (I’m using prompt on comboboxes). That is the process which results in that problem:
    1. Select an item from master combobox,
    2. Open the list of slave combobox,
    3. Close slave combobox without selecting any item,
    4. Select a different item from master combobox,
    5. Open the list of slave combobox,

    The problem shows up here. The list of slave combobox does not change, it shows the list of item that is selected in 1st step. But if I select an item after 5th step, i see right label on the slave one. I can explain using your example. You select USA then open state combobox(not select anything) and close it then select Canada on country combobox. When you open the state combobox you see USA’s state list but if you select the first one it shows Alberta (first state of the Canadian State list). There is a problem in labels I think because selection works correct but labels does not change. What can be the problem?

      1. I was also running into the display issue mentioned by GokcenG. I was able to work around this by switching the Flex SDK from version 3.5.12683 to 3.6.0.15427.

  31. Hi! I came across this entry while looking for an answer to my problem with two comboboxes.

    My problem is about two side-by-side comboboxes which have the same data (same dataprovider?) When an item has already been selected in the first combobox, I need for the second combobox to automatically remove that selection in its list so that it will not be listed anymore on that second combobox’s list. Can this be done? If so, please tell me how to do it. Thanks in advance.

  32. how can i get an url by selecting state? if i select ohio i want to call ohio.html, how ?

  33. Appreciate your post! Loved it. Flex Examples to me has become a standard authority to refer for easy to understand examples of flex applications. Thank you sir.

  34. Great example! How would this be done if you are not using an XML dataProvider for the Country ComboBox but are using a an ArrayCollection of Strings? So, based on the Country selection, you want to populate the State ComboBox with another ArrayCollection of Strings?

  35. This does not work for me. Granted, the example at the top works on this web page. But when I try to reproduce it with SDK 3.5 – changing the selection on the first ComboBox only sometimes changes the list in the second ComboBox.

    It is very irregular. I have tested and reproduced this in FB4 and FlashDevelop. FlashDevelop gives me an error “unable to bind to property on class ‘XML’ (class is not an IEventDispatcher)”

    What am I missing here? Thanks.

    1. just to answer my question above:

      var selects:Array = ['Country','State'];
       
      for (var i:int = 0; i &lt; selects.length; i++) {
      	var formItem:FormItem = new FormItem();
       
      	var comboBox:ComboBox = new ComboBox();
      	comboBox.id = selects[i];
      	comboBox.labelField = &#039;@name&#039;;
      	if (i == 0) {
      		comboBox.dataProvider = xml[selects[i]];
      	} else if (parentCB is ComboBox) {
      		BindingUtils.bindProperty(comboBox, &#039;dataProvider&#039;, parentCB, {name: &#039;selectedItem&#039;, getter: function (host:ComboBox):XMLList { return host.selectedItem.children(); }}, true);
      	}
      	formItem.addChild(comboBox);
      	form.addChild(formItem);
      }
  36. Thanks Pete for the init set up Works Great, but I need to take it one step further. Once a user gets to this page Im reading xml data to pre-populate the comboboxes so as to set Canada and Alberta. I have no issue getting Canada to show up but I cannot get the Alberta to show up. I have tried everything and still no answer.

    pre-populate with this: parentDocument.getEvent.lastResult.events.event.manufacturer_state

    Thanks, Mark

  37. I am trying to create an autocomplete textbox/combobox for streetnames. There are around 1.4M street addresses I want in there. I have tried using XML for the datasource but it’s too slow. I was hoping I can use a table in SQL Server as the datasource instead. I’m sure this is possible but I am a Flex newbie and not sure how to do this. Will it be any faster getting the data from SQL Server, than XML?

Comments are closed.