6 Replies Latest reply on Mar 29, 2010 8:41 AM by wbnc1902

    Combobox data value

    wbnc1902

      Hello all,

      I have what should be a simple problem to solve, but I am new to Flex and Google has failed me.  I am working on a Flex application where I have a combo box that has a database query as the data provider. All is working fine except one small detail.  I want to have the label show a name, but the value of that label to be a number.  For example my database table has names in it that are associated with an ID that is the primary key:

       

      NameID
      John Doe1
      Jane Doe2
      Jim Jones3

       

       

      I would like the combo box to show the user the name, but the value of what is selected is the number.  How do I do this in flex?  If I were doing this in ColdFusion it would be easy, but I cannot figure out how to do this in Flex.  In ColdFusion I would do something like:

       

       

      In this example the user would be shown a simple drop down with names, but behind the scenes you would actually be selecting the ID of that name which is needed for a future query.

       

      It is possible that I am so used to programming ColdFusion that I am going about this entirely wrong, however I do not know where to start looking.

       

      Any help would be greatly appreciated.

        • 1. Re: Combobox data value
          Peter deHaan Level 4

          @wbnc1902,

           

          You can use the selectedItem object to get the item in the data provider, as seen in the following example:

           

          <?xml version="1.0" encoding="utf-8"?>

          <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">

           

              <mx:Script>

                  <![CDATA[

                      import mx.controls.Alert;

                      protected function button1_clickHandler(evt:MouseEvent):void {

                          var item:Object = cBox.selectedItem;

                          Alert.show("label: " + cBox.selectedLabel + "\n" + "value: " + item.value);

                      }

                  ]]>

              </mx:Script>

           

           

              <mx:ComboBox id="cBox">

                  <mx:dataProvider>

                      <mx:Array>

                          <mx:Object label="John Doe" value="1" />

                          <mx:Object label="Jane Doe" value="2" />

                          <mx:Object label="Jim Jones" value="3" />

                      </mx:Array>

                  </mx:dataProvider>

              </mx:ComboBox>

           

              <mx:Button label="get stuff" click="button1_clickHandler(event);" />

           

          </mx:Application>

          Peter

          • 2. Re: Combobox data value
            wbnc1902 Level 1

            Peter,

               Thank you for the quick response and detailed example, however I am still confused.  Using your example I would have to "hard code" the data provider for my combo box.  Is there anyway to do the same thing dynamically?

             

            Here is my current code:

            <?xml version="1.0" encoding="utf-8"?>
            <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="init()">
                 
            <mx:Script>
                 <![CDATA[
            
                      import mx.rpc.events.ResultEvent;
                      import mx.collections.ArrayCollection;
                      
                      [Bindable]
                      private var myData:ArrayCollection;
                      
                      private function init():void
                      {
                           myService.getName();
                      }
                      
                      private function resultHandler(event:ResultEvent):void
                      {
                           myData = event.result as ArrayCollection;
                      }
                      
            
                 ]]>
            </mx:Script>
            
                 <mx:RemoteObject id="myService" destination="ColdFusion" source="flexCFtester.remoteTest-debug.cfc.PersonService" showBusyCursor="true" result="resultHandler(event)" />     
                      
                 <mx:ComboBox dataProvider="{myData}" labelField="countyName" id="countyName"/><mx:Button label="Select County" click="currentState='getDate'"/>
                      
                      
            
                 
                 
            </mx:Application>
            

             

             

            There are hundreds of names and typing them in as you have is not piratical considering names might be added or removed from the database.  Do you have any other ideas?

             

            Again, thank you so much for your help.

             

            Will

            • 3. Re: Combobox data value
              Matt Le Fevre Level 4

              if it's been simply fed an arrayCollection, you should be able to reel it off like this

               

              countyName.selectedItem.ID

               

              changing 'ID' to whatever hidden node you wish to output. Then try something like:

               

              <mx:ComboBox dataProvider="{myData}" labelField="countyName" id="countyName" change="trace(countyName.selectedItem.ID
              )
              "/>

               

              and see if that starts outputting the ID number in the flex console.

               

               

              it works in this quick example i just wrote

               

              <?xml version="1.0" encoding="utf-8"?>
              <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical">
                  
              
                  <mx:XMLList id="people">
                      <person>
                          <FirstName>John</FirstName>
                          <uniqueID>994563</uniqueID>
                      </person> 
                      <person>
                          <FirstName>Sally</FirstName>
                          <uniqueID>123564</uniqueID>
                      </person> 
                      <person>
                          <FirstName>Mary</FirstName>
                          <uniqueID>131233</uniqueID>
                      </person> 
                      <person>
                          <FirstName>Robert</FirstName>
                          <uniqueID>33324</uniqueID>
                      </person> 
                  </mx:XMLList>
                  <mx:ComboBox id="testCombo" dataProvider="{people}" labelField="FirstName" change="trace(testCombo.selectedItem.uniqueID)"/>
                  
              </mx:Application>
              
              

               

              same theory behind it. Allows you to access a hidden field quickly without displaying it directly to the user.

               

              Let me know if that's what you wanted

              • 4. Re: Combobox data value
                kubens Level 2

                I had a similar requirement durring the last days. To solve that I have created a new DropDownList component that extends the standard DropDownList component:

                 

                package net.woocoom.components.controls
                {
                    import spark.components.DropDownList;
                    import spark.events.IndexChangeEvent;

                    public class DropDownList extends spark.components.DropDownList
                    {
                       
                        /**
                         * @private
                         * Field that contains the name of binded field
                         */
                        private var _dataField:String;
                        public function get dataField():String
                        {
                            return _dataField;
                        }       
                        [Bindable] public function set dataField(value:String):void
                        {
                            if (_dataField == value)
                                return;
                           
                            _dataField = value;
                        }
                       
                        /**
                         * @private
                         * Field that contains the value of selected item.
                         */
                        private var _value:*;
                        [Bindable ("valueChanged")]
                        public function get value():*
                        {
                            var value:* = selectedItem;
                            if (dataField != '' && selectedItem && selectedItem.hasOwnProperty(dataField))
                            {
                                value = selectedItem[dataField];
                            }
                           
                            return value;
                        }
                        public function set value(newValue:*):void
                        {
                            if (dataField != '' && newValue.hasOwnProperty(dataField))
                            {
                                if (_value == newValue[dataField])
                                    return;
                               
                                _value = newValue[dataField];
                            }
                            else
                            {
                                if (_value == newValue)
                                    return;
                               
                                _value = newValue;
                            }
                           
                            // synchronize selected index with assigned value
                            var index:int=-1;
                            for (var i:int=0; i <dataProvider.length; i++)
                            {
                                if (dataProvider[i] != null &&
                                    dataProvider[i].hasOwnProperty(dataField) &&
                                    dataProvider[i][dataField] == _value)
                                {
                                    index=i;
                                    break;
                                }
                            }
                            selectedIndex=index;
                           
                            // fire event for data binding
                            dispatchEvent(new Event("valueChanged"));
                        }
                       
                        /**
                         * Constructor
                         */        
                        public function DropDownList()
                        {
                            addEventListener(IndexChangeEvent.CHANGE, function(event:IndexChangeEvent):void{ value = selectedItem; });           
                        }
                    }
                }

                 

                Inside my form I have two data services:

                 

                <wakvalueobjects:News  fx:id="valueObject"/>

                 

                <s:CallResponder id="getResult" result="valueObject = getResult.lastResult as News"/>
                <wakservices:NewsService id="dataService" showBusyCursor="true" />

                 

                <s:CallResponder  id="getResultNewsCategory" result="valueObject = getResultNewsCategory.lastResult as NewsCategory"/>

                <wakservices:NewsCategoryService  id="dataServiceNewsCategory" showBusyCursor="true" />

                 

                My enhanced DropDownList is binded to valueObject.category.id but dataProvider is listResultNewsCategory.lastResult

                 

                <mx:FormItem label="Category" labelWidth="120" required="true">
                <wakcontrols:DropDownList id="categoryDropDownList" labelField="name" dataProvider="{listResultNewsCategory.lastResult}" dataField="id" value="@{valueObject.category.id}" width="200" />
                </mx:FormItem>

                 

                You can see an running example on my playground.

                Hope that was what you are looking for ;-)

                 

                Wolfgang

                1 person found this helpful
                • 5. Re: Combobox data value
                  wbnc1902 Level 1

                  Genius!

                   

                  Thank you for your help.  I was doing two things wrong, I was not referencing the id of the selected item.  I was referencing the "Data" which didn't exsist in the database.  I also forgot that flex is case sensitive!  ID != id.

                   

                  Thanks again for your help!

                   

                  Will

                  • 6. Re: Combobox data value
                    wbnc1902 Level 1

                    Wolfgang,

                        Your solution also works well however a bit overkill for my needs.  Your app on your website is pretty cool.  I love how flex just "feels".  Everything is so crisp and clean.  I really need to learn more about it because i want to convert all my web apps to flex apps sometime soon.

                     

                    Thanks again for your post and helpful remarks.

                     

                    Will