Wednesday, March 25, 2009

The LabelFunction, ComboBox

Hello All, this is my first post and I starting with something that could be very fun for newbies. This is a simple way to change how the information contained on a ArrayCollection is showed on a ComboBox simple but this could be useful if you are getting an Array of objects, and each Object containing the name and last name from the users of a DataBase. And making thinks a little bit complex, depending on the country of the user you can display the information in one of this two ways:

for US - Last Name, First Name

for PT - First Name, Last Name But in order to do that more things are needed and that is another Post ;) So lets go do this in 3 easy steps: STEP 1 The ArrayCollection contains a simple Object with 2 parameters,

var temp:Object = new Object();

temp.name

temp.number

just for fun, I create that complex verification to know when the variable i is pair or not.

Then I add each new filled object temp to the myDataProvider (the ArrayCollection) variable.

STEP 2

create the ComboBox, defining the dataprovider and the labelFuntion

<mx:ComboBox dataProvider=" { myDataProvider } " labelFunction=" createLabel " />

Ok, now you can ask what is a labelFuncion?

The labelFunction is a property of the ComboBox (and other components) that let you provide a function that will handle each item of the dataProvider, and create a String that will be our label to display on the ComboBox.

STEP 3

The labelFunction:

private function createLabel(value:Object):String{

var out:String;

out = value.name + " : " + value.number;

return out;

}

as you can see this is a very simple function, but the complexity of the function will be defined by the complexity of your data, and how you want to show it, the thing that you always keep in mind is the labelFunction will recibe ALWAYS an Object and provide a String as result of whatever you do inside.

The Object you receive from the ComboBox, as I told before, is one item of the dataProvider, in this case an Object that represent the original temp Object.

I really hope that you find this example easy to understand and that could be useful for you.

See you soon :D