A custom function to convert new data items to the format required by the data provider
<!--
Code from Flex 4 Documentation "Using Adobe Flex 4".
This user guide is licensed for use under the terms of the Creative Commons Attribution
Non-Commercial 3.0 License.
This License allows users to copy, distribute, and transmit the user guide for noncommercial
purposes only so long as
(1) proper attribution to Adobe is given as the owner of the user guide; and
(2) any reuse or distribution of the user guide contains a notice that use of the user guide is governed by these terms.
The best way to provide notice is to include the following link.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/
-->
<!-- dpcontrols\spark\SparkCBAddItemObj.mxml -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<s:layout>
<s:VerticalLayout paddingTop="5" paddingLeft="5" />
</s:layout>
<fx:Script>
import spark.events.IndexChangeEvent;
// Define a custom function for the labelFunction property
// to display an Object in the ComboBox control.
public function myLabelFunc(item:Object):String {
return item.firstName + " " + item.lastName;
}
// Define a custom function for the labelToItemFunction property
// to convert the new value to an Object of the correct format
// for storage in the data provider of the control.
public function myLabelToItemFunc(value:String):Object {
var tempObj:Object = new Object();
var spaceChar:int = value.indexOf(' ');
tempObj.firstName = value.substr(0, spaceChar);
tempObj.lastName = value.substr(spaceChar+1, value.length);
return tempObj;
}
// Event handler to determine if the selected item is new.
protected function myCB_changeHandler(event:IndexChangeEvent):void
{
// Determine if the index specifies a new data item.
if(myCB.selectedIndex == spark.components.ComboBox.CUSTOM_SELECTED_ITEM)
// Add the new item to the data provider.
myCB.dataProvider.addItem(myCB.selectedItem);
}
</fx:Script>
<s:Label text="The selected index is: {myCB.selectedIndex}" />
<s:Label text="The selected item is: {myCB.selectedItem.firstName + ' ' + myCB.selectedItem.lastName}" />
<s:ComboBox id="myCB" width="140" labelFunction="myLabelFunc"
labelToItemFunction="myLabelToItemFunc"
change="myCB_changeHandler(event);">
<s:dataProvider>
<mx:ArrayList>
<fx:Object firstName="Steve" lastName="Smith" />
<fx:Object firstName="John" lastName="Jones" />
<fx:Object firstName="Mary" lastName="Moore" />
</mx:ArrayList>
</s:dataProvider>
</s:ComboBox>
</s:Application>
Related examples in the same category