How to create an ArrayCollection of Objects? - apache-flex

I new to flex, I have a class shown below:
public class Items extends Object
{
public function Items(){
super();
}
public var name:String;
public var count:int;
}
How do I create an ArrayCollection of type Items?
Thanks.

var item1:Items = new Items();
item1.name = "Name1";
item1.count = 5;
var item2:Items = new Items();
item2.name = "Name2";
item2.count = 7;
var items:ArrayCollection = new ArrayCollection([item1, item2]);
Another way:
var items:ArrayCollection = new ArrayCollection();
var item1:Items = new Items();
item1.name = "Name1";
item1.count = 5;
items.addItem(item1);
var item2:Items = new Items();
item2.name = "Name2";
item2.count = 7;
items.addItem(item2);

You can also create these in mxml (inside if you're using flex 4)
<s:ArrayCollection id="theCollection">
<namespace:Items name="name 1" count="5" />
<namespace:Items name="name 2" count="6" />
<namespace:Items name="name 3" count="7" />
<namespace:Items name="name 4" count="8" />
</s:ArrayCollection>
Then reference the array by its id.

Somewhere in your code:
var ac : ArrayCollection = new ArrayCollection();
var newItem : Items = new Items();
newItem.name = 'some value';
newItem.count = 1;
ac.addItem(newItem);
newItem = new Items();
newItem.name = 'some other value';
newItem.count = 2;
ac.addItem(newItem);
newItem = new Items();
newItem.name = 'Yet another value';
newItem.count = 3;
ac.addItem(newItem);
...
It may be worth nothing that ArrayCollections are not typed in the same way that a Vector may be, so there is nothing you can do to force all items in your collection to be of the Items type. [Unless you extend ArrayCollection somehow and override the addItem / addItemAt methods to throw errors if the type is wrong.

Related

Flex 3: Setting one arrayCollection to another is stalling the application

I'll just go ahead and C/P the entire function to ensure you guys see everything going on:
public function directorsPrepsToShow():void
{
var tempDPrepsAC:ArrayCollection = new ArrayCollection;
var dprepSD:Date = new Date;
var dprepED:Date = new Date;
var viewSD:Date = rightDate(startViewDate.getMonth(), startViewDate.getDate(), startViewDate.getFullYear());
var viewED:Date = rightDate(viewSD.getMonth(), viewSD.getDate() + 14, viewSD.getFullYear());
var newACIDs:String = new String;
var useACIDs:String = new String;
for each (var item:Object in dPrepAC)
{
dprepSD = textToDate(item[2]);
dprepED = rightDate(dprepSD.getMonth(), Number(dprepSD.getDate() + (item[3] - 1)), dprepSD.getFullYear());
if (dateCollider(dprepSD, dprepED, viewSD, viewED))
tempDPrepsAC.addItem(item as Array);
}
if (tempDPrepsAC.length != usePrepAC.length)
{
usePrepAC = new ArrayCollection();
usePrepAC = tempDPrepsAC;
Alert.show("HI");
}
}
This function is in a separate file, that's called from the main mxml via the following:
<mx:Script source="functions/dprep.as" />
The line that's causing the app to stall is "usePrepAC = tempDPrepAC;". usePrepAC is declared in the main mxml like this:
[Bindable] public var usePrepAC:ArrayCollection = new ArrayCollection;
Dose anybody see why this one line would cause the application to stall? If I comment out that line, the application loads fine (loads everything except for the information that this AC should contain). I've been looking at this now for about an hour, trying different ways to get the contents of tempDPrepsAC into usePrepAC - but nothing is working. I tried googling it, but found nothing :(
Thanks,
Brds
EDIT
dprep AC is declared in the main mxml like this:
[Bindable] public var dPrepAC:ArrayCollection = new ArrayCollection;
And the function that populates it is as follows:
public function createDirectorsPrepCollection(e:ResultEvent):void
{
var xmlList:XMLList = XML(e.result).directorsprep;
var dupString:String = "|";
var tempArray:Array = new Array;
for (var i:int = 0; i < xmlList.length(); i++)
{
if (dupString.indexOf(String("|" + xmlList[i].name.#id) + "|") == -1)
{
tempArray = new Array;
tempArray[0] = xmlList[i].prepDBID;
tempArray[1] = xmlList[i].projectDBID;
tempArray[2] = xmlList[i].startdate;
tempArray[3] = xmlList[i].numdays;
tempArray[4] = xmlList[i].positions;
dPrepAC.addItem(tempArray);
dupString += "|" + xmlList[i].prepDBID + "|";
}
}
directorsPrepsToShow();
}
This function is called by this:
<mx:HTTPService id="dprepHttp" url="{dprepXML}" resultFormat="e4x" makeObjectsBindable="true" result="createDirectorsPrepCollection(event)" />
dPrepAC is populating fine btw... I check it in a for each loop.
Try using following code:
usePrepAC.source = tempDPrepsAC.source;

How to read the Dynamic form Child data in Flex?

i created a form dynamically by adding each component in action script,
now i want to get back the text/data entered in to that each component dynamically?
private function loadAllComponents():void
{
var formItemArray:Array = new Array();
for(var i:int=0; i< Application.application.designList.length; i++)//which had the colonName, colComponet to be dispalyed,
{
var fm:FormItem = new FormItem();
fm.label = Application.application.designList.getItemAt(i).colName;
var comp:String = Application.application.designList.getItemAt(i).component;
switch(comp)
{
case "TextBox":
var ti:TextInput = new TextInput();
ti.id = Application.application.designList.getItemAt(i).component;
fm.addChild(ti);
break;
case "TextArea":
var ta:TextArea = new TextArea();
ta.id = Application.application.designList.getItemAt(i).colName;
fm.addChild(ta);
break;
case "ComboBox":
var mycb:myComboBox = new myComboBox();
mycb.getAllMasterCBData(Application.application.selectedgridItem, Application.application.designList.getItemAt(i).colName);
fm.addChild(mycb);
break;
case "DateField":
var df:DateField = new DateField();
df.id = Application.application.designList.getItemAt(i).component;
fm.addChild(df);
break;
}
myform.addChild(fm);
}
}
private function saveToDb():void // Here i wan to read all the formdata
{
var formItems:Array = myform.getChildren();
for each (var item:UIComponent in formItems)
{
if (item is TextInput)
{
var text:String = Object(item).text;
Alert.show("came here");
}
else if (item is DateField)
{
var date:Date = DateField(item).selectedDate;
}
}
}
]]>
</mx:Script>
<mx:Form id="myform" cornerRadius="5" borderColor="#B7BABC" borderStyle="solid" width="100%" height="100%" />
<mx:HBox width="100%" height="100%" >
<mx:Spacer width="120"/>
<mx:Button label=" Save " id="saveBtn" click="saveToDb()" />
</mx:HBox>
You're creating the input components in ActionScript, but based on this code you are not creating them dynamically; you're just hard coding them. With your given sample, you'll know the components you are creating at compile time.
You'll need to store a reference to the form items you create; make them public variables instead of 'var' local variables. Kind of like this:
protected var ti:TextInput ;
protected var ta:TextArea ;
protected var df:DateField;
Then in your creation method, do something like this:
ti = new TextInput();
ti.id = Application.application.designList.getItemAt(i).component;
fm.addChild(ti);
ta = new TextArea();
ta.id = Application.application.designList.getItemAt(i).colName;
fm.addChild(ta);
df = new DateField();
df.id = Application.application.designList.getItemAt(i).component;
fm.addChild(df);
myform.addChild(fm);
Then when you need to access them, just do something like this:
private function getMyformData()
{
ti.text;
ta.text;
}
If you're generating the form components at run time based on data, then store then form elements in an array of some sort.
You could also work something out by looping over all children of your container, although that wouldn't be my first approach.
Since poster posted more complete code; here are some additions. I added the protected array of all form items and in each 'switch' block; the new input element is pushed onto the array.
<mx:Script>
protected var itemsArray : Array = new Array();
private function loadAllComponents():void
{
var formItemArray:Array = new Array();
for(var i:int=0; i< Application.application.designList.length; i++)//which had the colonName, colComponet to be dispalyed,
{
var fm:FormItem = new FormItem();
fm.label = Application.application.designList.getItemAt(i).colName;
var comp:String = Application.application.designList.getItemAt(i).component;
switch(comp)
{
case "TextBox":
var ti:TextInput = new TextInput();
ti.id = Application.application.designList.getItemAt(i).component;
fm.addChild(ti);
itemsArray.push(ti)
break;
case "TextArea":
var ta:TextArea = new TextArea();
ta.id = Application.application.designList.getItemAt(i).colName;
fm.addChild(ta);
itemsArray.push(ta)
break;
case "ComboBox":
var mycb:myComboBox = new myComboBox();
mycb.getAllMasterCBData(Application.application.selectedgridItem, Application.application.designList.getItemAt(i).colName);
fm.addChild(mycb);
itemsArray.push(mycb)
break;
case "DateField":
var df:DateField = new DateField();
df.id = Application.application.designList.getItemAt(i).component;
fm.addChild(df);
itemsArray.push(df)
break;
}
myform.addChild(fm);
}
}
The sateToDb method will change to be something like this:
private function saveToDb():void // Here i wan to read all the formdata
{
var formItems:Array = myform.getChildren();
for each (var item:UIComponent in itemsArray )
{
if (item is TextInput)
{
var text:String = Object(item).text;
Alert.show("came here");
}
else if (item is DateField)
{
var date:Date = DateField(item).selectedDate;
}
}
}
]]>
</mx:Script>
Edited Response:
OK, I think I see the issue.
You're adding your data controls to FormItems and adding those to the Form. But then you're iterating over the Form's children and as if they were the data controls and not FormItems.
Without commenting on the rest of the code, have a look at what this updated function is doing to retrieve the data controls:
private function saveToDb():void
{
var formItems:Array = myform.getChildren();
for each (var item:FormItem in formItems)
{
var itemChildren:Array = item.getChildren();
for each (var control:UIComponent in itemChildren)
{
if (control is TextInput)
{
var text:String = Object(item).text;
Alert.show("TextInput");
}
else if (control is DateField)
{
var date:Date = DateField(item).selectedDate;
Alert.show("Date");
}
}
}
You can delete the formItemArray variable too, it's not needed since we're getting the list of children from the Form and FormItems.
Original response:
If you keep a reference to each of the dynamic form items in an Array you can iterate over each of them in your getMyFormData() function.
e.g.
protected var formItems:Array = new Array();
// Other class stuff here...
var ti:TextInput = new TextInput();
ti.id = Application.application.designList.getItemAt(i).component;
formItems.push(ti); // Add item to array.
fm.addChild(ti);
var ta:TextArea = new TextArea();
ta.id = Application.application.designList.getItemAt(i).colName;
formItems.push(ta); // Add item to array.
fm.addChild(ta);
var df:DateField = new DateField();
df.id = Application.application.designList.getItemAt(i).component;
formItems.push(df); // Add item to array.
fm.addChild(df);
myform.addChild(fm);
<mx:button click="getMyformData()"/>
private function getMyformData()
{
//How to get the myform Data dynamically here after validations... ? &
for each (var item:UIComponent in formItems)
{
if (item is TextInput || item is TextArea)
{
// Cast to Object to access the 'text' property without the compiler complaining.
var text:String = Object(item).text;
// Do something with the text...
}
else if (item is DateField)
{
var date:Date = DateField(item).selectedDate;
// Do something with the date...
}
// Insert additional type checks as needed.
}
}
You'll have to work out what to do with the data on your own though :)
If you are using a separate list make sure you clear out the formItems array when you're done with it so you don't have references to the items keeping them in memory unnecessarily.
Instead of keeping a separate array of form items you could also iterate over the children in the fm container. You might have to make some assumptions about the children you'd be accessing but it looks like you have control over all of the children being added so that's no problem.
I hope that helps...
:)

Doubt in action script for Flex: getting unique elements from an ArrayCollection

I have an ArrayCollection as mentioned below.
private var initDG:ArrayCollection = new ArrayCollection([
{fact: "Order #2314", appName: "AA"},
{fact: "Order #2315", appName: "BB"}
{fact: "Order #2316", appName: "BB"}
...
{fact: "Order #2320", appName: "CC"}
{fact: "Order #2321", appName: "CC"}
]);
I want to populate a ComboBox with UNIQUE VALUES of "appName" field from the ArrayCollection initDG.
<mx:ComboBox id="appCombo" dataProvider="{initDG}" labelField="appName"/>
One method I could think is to loop through the Array objects and for each object check and push unique appName entries into another Array. Is there any better solution available?
That sounds good to me:
var unique:Object = {};
var value:String;
var array:Array = initDG.toArray();
var result:Array = [];
var i:int = 0;
var n:int = array.length;
for (i; i < n; i++)
{
value = array[i].appName;
if (!unique[value])
{
unique[value] = true;
result.push(value);
}
}
return new ArrayCollection(result);
You can used this class for finding unique arraycollection:
tempArray=_uniqueArray.applyUnqiueKey1(_normalsearchdata.toArray());
"uniqueArray" this is package name and _normalsearchdata is ArrayCollection;
package{
import mx.collections.ArrayCollection;
public class applyUniqueKey{
private var tempArray:Array;
private var tempIndex = 0;
public var temp:String;
public function applyUnqiueKey1(myArray)
{
tempArray = new Array();
tempIndex = 0;
myArray.sort();
tempArray[0] = myArray[0];
tempIndex++;
for(var i=1; i<myArray.length; i++) {
if(myArray[i] != myArray[i-1]) {
tempArray[tempIndex] = myArray[i];
tempIndex++;
}
}
var temp=String(tempArray.join());
return new ArrayCollection(tempArray);
}
}
}
Alas, there is no unique() method in ActionScript's Array, but you can approximate it like this:
var names:Array = initDG.toArray().map(
function (e:Object, i:Number, a:Array):String {
return e.appName;
}
);
var uniqueNames:Array = names.filter(
function (name:String, i:Number, a:Array):Boolean {
// Only returns true for the first instance.
return names.indexOf(name) == i;
}
);
Note this happens to work because you are filtering strings, which are compared by value. This wouldn't be effective if you needed to filter arbitrary objects.

Disabling radiobuttongroup

Since Repeater component won't generate radiobuttongroup in mxml, and since I can't do the same through ActionScript because radiobuttongroup doesn't have an id property when I try to create it that way, is there a way to disable radiobuttons at all? As far as I can see, the only thing I can set and access is groupName property of radiobuttons.
For Repeater component I tried using xml directly
<mx:XML id="xquiz" source="quiz.xml" />
with this code:
<mx:Repeater dataProvider="{xquiz.question}" id="rep">
<mx:Label text="{rep.currentItem.content}" />
<mx:Repeater dataProvider="{rep.currentItem.answer}" id="rep2">
<mx:RadioButton label="{rep2.currentItem}" groupName="{'rbg'+rep.currentIndex}" click="checkAnswers(event)" value="{rep2.currentItem.#correct}" />
</mx:Repeater>
</mx:Repeater>
and cannot use repeater to generate radiobuttongroup since it's not a visible component.
I also tried ActionScript approach but with HTTPService mxml component to fetch xml file.
<mx:HTTPService id="srv" url="quiz.xml" resultFormat="e4x" result="handleResult(event);" fault="handleFault(event);"/>
and here's actionscript snippet:
private var xQuizData:XML
private function handleResult(event:ResultEvent):void {
xQuizData = event.result as XML;
initApp();
}
private function initApp():void {
var cnt:Number = 0;
for each (var question:XML in xQuizData.*) {
var lbl:Label = new Label();
lbl.text = question.content;
panel.addChild(lbl);
lbl.visible = true;
var cnt2:Number = 0;
for each (var answer:XML in question.answer) {
var rb:RadioButton = new RadioButton();
rb.id=String(cnt);
rb.label=answer;
rb.groupName="rbg"+String(cnt);
if (answer.hasOwnProperty("correct")) {
rb.value=true;
}
panel.addChild(rb);
rb.visible = true;
cnt2++;
}
cnt++;
}
}
I want to be able to catch clicks from radiobuttongroup controls, but can't get them to generate at all if with repeater or can't assign them id if with actionscript.
XML contents would look something like this:
<quiz>
<question>
<content>Some question?</content>
<answer>Answer one</answer>
<answer correct="true">Answer two</answer>
<answer>Answer three</answer>
<answer>Answer four</answer>
</question>
</quiz>
I'm having a hard time following what you are trying to do from your snippets, so here's a snippet of mine that should do exactly what your wanting. Hopefully you can review it and adapt it for your problem.
public function buildVBox():void{
tempVBox.removeAllChildren();
var iterator:Number = 0;
for each (var i:XML in myXML.children()){
var tempCanv:Canvas = new Canvas();
tempCanv.id = iterator.toString();
var tempRadYes:RadioButton = new RadioButton;
tempRadYes.x = 30;
tempRadYes.y = 20;
tempRadYes.origY = 20;
tempRadYes.groupName = "rbg" + iterator.toString();
tempRadYes.value = 1;
tempRadYes.label = "Yes"
tempCanv.addChild(tempRadYes);
var tempRadNo:extRadioButton = new extRadioButton;
tempRadNo.x = 80;
tempRadNo.y = 20;
tempRadNo.origY = 20;
tempRadNo.groupName = "rbg" + iterator.toString();
tempRadNo.value = 2;
tempRadNo.label = "No"
tempCanv.addChild(tempRadNo);
var tempRadNA:extRadioButton = new extRadioButton;
tempRadNA.x = 120;
tempRadNA.y = 20;
tempRadNA.origY = 20;
tempRadNA.groupName = "rbg" + iterator.toString();
tempRadNA.value = 0; tempRadNA.label = "N/A"
tempCanv.addChild(tempRadNA);
tempVBox.addChild(tempCanv);
iterator++;
}
}
Got a solution from here: http://www.jonathanrowny.com/journal/radiobuttongroup-inside-repeater

How to generate a form(<mx:form>) dynamically in flex?

I need to generate a mx:form from an xml file that I am getting from httpservice.
Also I need to prefill the data that I am getting from the form itself.
Can someone give me a sample code?
You would have to expand on this obviously, but this is how I would go about building a dynamic form..
import mx.controls.TextInput;
import mx.containers.FormItem;
import mx.containers.Form;
private var fxml:XML =
<form>
<fields>
<field type="text" label="name" default="gary"/>
<field type="text" label="surname" default="benade"/>
</fields>
</form>
private function init():void
{
var form:Form = new Form();
form.setStyle("backgroundColor", 0xFFFFFF);
for each( var xml:XML in fxml..field)
{
switch( xml.#type.toString())
{
case "text":
var fi:FormItem = new FormItem();
fi.label = xml.#label;
var ti:TextInput = new TextInput();
ti.text = xml.#default.toString();
fi.addChild( ti);
form.addChild( fi);
break;
case "int":
break;
}
}
this.addChild( form);
}
Check this out: MXMLLoader for Flex 3. HTH.
<?xml version="1.0" encoding="utf-8"?>
<s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="handleCreationComplete()">
<fx:Declarations>
<fx:XML id="formdata">
<userinfoform>
<user>
<firstname inputtype="TextInput" formlabel="First Name" required="true">true</firstname>
<lastname inputtype="TextInput" formlabel="Last Name" required="true">true</lastname>
<Middlename inputtype="TextInput" formlabel="Middle Name" required="false">true</Middlename>
<nickname inputtype="TextInput" formlabel="Nick Name" required="false">false</nickname>
<combobox inputtype="ComboBox" formlabel="Gender" required="true">Male,Female</combobox>
<type inputtype="ComboBox" formlabel="Type" required="false">Book,Cds,Games</type>
<radioButtonGroup inputtype="RadioButtonGroup" formlabel="Gender" required="false">
<radiobutton inputtype="RadioButton" formlabel="Gender" required="true">Male</radiobutton>
<radiobutton inputtype="RadioButton" formlabel="Gender" required="true">Female</radiobutton>
</radioButtonGroup>
</user>
</userinfoform>
</fx:XML>
</fx:Declarations>
`enter code here`<fx:Script>
<![CDATA[
import flashx.textLayout.events.SelectionEvent;
import mx.collections.ArrayCollection;
import mx.core.UIComponent;
import mx.events.ItemClickEvent;
import mx.events.ValidationResultEvent;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.validators.NumberValidator;
import mx.validators.StringValidator;
import spark.components.ComboBox;
import spark.components.DropDownList;
import spark.components.RadioButton;
import spark.components.RadioButtonGroup;
import spark.components.TextArea;
import spark.components.Form;
import spark.components.FormItem;
import spark.components.TextInput;
import spark.components.RadioButtonGroup;
import spark.components.RadioButton;
private function handleCreationComplete():void
{
//Below line can be used for XML from an external source
//XMLService.send();
buildForm(new XML(formdata));
}
private function errorHandler(evt:FaultEvent):void
{
//Alert.show("Error: " + evt.fault.message);
}
private function resultHandler(evt:ResultEvent):void
{
buildForm(new XML(evt.result));
}
private function buildForm(xml:XML):void
{
var lst:XMLList = xml.children();
for(var i:int = 0; i < lst.length(); i++)
{
var x:XMLList = lst[i].children();
for(var j:int = 0; j < x.length(); j++)
{
if(x[j].#inputtype == 'TextInput')
{
var frmItem:FormItem = new FormItem();
//frmItem.direction = "horizontal";
frmItem.label = x[j].#formlabel;
// make sure boolean is pasrsed to a string before assigned
// to required property of the formitem
var validString : String = x[j].#required;
var valid : Boolean = (validString == "true");
frmItem.required = valid;
var tb:TextInput = new TextInput();
tb.text = x[j];
frmItem.addElement(tb);
userInfoForm.addElement(frmItem);
}
else if(x[j].#inputtype == 'ComboBox')
{
var frmItemCB:FormItem = new FormItem();
//frmItemCB.direction = "horizontal";
frmItemCB.label = x[j].#formlabel;
// make sure boolean is pasrsed to a string before assigned
// to required property of the formitem
var validString : String = x[j].#required;
var valid : Boolean = (validString == "true");
frmItemCB.required = valid;
// make sure the string is split, assigned to an array, and parsed
// to an arraycollection to assgn it as dataprovider for dropdownlist
var str:String = x[j];
var arr:Array = str.split(",");
var arrcol:ArrayCollection = new ArrayCollection();
for(var k:int = 0; k < arr.length; k++)
{
var obj:Object = {name:arr[k]}
arrcol.addItem(obj);
}
var cb:DropDownList = new DropDownList();
cb.dataProvider = arrcol;
cb.labelField = "name";
frmItemCB.addElement(cb);
userInfoForm.addElement(frmItemCB);
}
else if(x[j].#inputtype == 'RadioButtonGroup')
{
var frmItemRB:FormItem = new FormItem();
//frmItemRB.direction = "horizontal";
frmItemRB.label = x[j].#formlabel;
// make sure boolean is pasrsed to a string before assigned
// to required property of the formitem
var validString : String = x[j].#required;
var valid : Boolean = (validString == "true");
frmItemRB.required = valid;
var frmItemRB1:FormItem = new FormItem();
frmItemRB1.addElement(label);
var y:XMLList = x[j].children();
var radioGroup = new RadioButtonGroup();
radioGroup.addEventListener(ItemClickEvent.ITEM_CLICK,
radioGroup_itemClick);
for(var l:int = 0; l < y.length(); l++)
{
var rb = new RadioButton();
rb.label = y[l];
rb.group = radioGroup;
frmItemRB.addElement(rb);
userInfoForm.addElement(frmItemRB);
}
}
}
}
}
public var label:TextInput = new TextInput();
private function radioGroup_itemClick(evt:ItemClickEvent):void {
label.text = evt.label ;
}
/**
* Helper function that returns all the fields for a
* given form. Pass in requiredOnly = true if you only want
* the required fields.
*/
private function getFields(form:Form, requiredOnly:Boolean=false):Array
{
var a:Array = [];
return a;
}
/**
* Validates all fields in a given form.
*/
private function validateForm(form:Form):Boolean
{
// reset the flag
var _isValid:Boolean = true;
var _notValid:Boolean = false;
// populate the fields - if your fields aren't dynamic put this in creationComplete
var fields:Array = getFields(form, true);
for each(var source:UIComponent in fields)
{
// create a simple string validator
var stringValidator:StringValidator = new StringValidator();
stringValidator.minLength = 2;
stringValidator.source = source;
stringValidator.property = "text";
stringValidator.requiredFieldError = "This field is required!!!";
var numberValidator:NumberValidator = new NumberValidator();
numberValidator.minValue = 0;
numberValidator.source = source;
numberValidator.property = "text";
numberValidator.lowerThanMinError = "This field is required!!!";
var rbValidator:StringValidator = new StringValidator();
rbValidator.minLength = 1;
rbValidator.maxLength = 80;
rbValidator.source = source;
rbValidator.property = "selectedValue";
rbValidator.requiredFieldError = "This field is required!!!";
var result:ValidationResultEvent;
//var radiogroup:spark.components.RadioButtonGroup = new spark.components.RadioButtonGroup;
// typical validation, but check to this checks for any different
// types of UIComponent here
if (source is TextInput)
result = stringValidator.validate(TextInput(source).text)
else if (source is TextArea)
result = stringValidator.validate(TextArea(source).text)
else if (source is DropDownList)
result = numberValidator.validate(DropDownList(source).selectedIndex)
//else if (source is Label)
//result = stringValidator.validate(Label(source).text)
//if(source is spark.components.RadioButton)
//result = numberValidator.validate(mx.controls.RadioButton(source))
// if the source is valid, then mark the form as valid
_isValid = (result.type == ValidationResultEvent.VALID) && _isValid;
}
return _isValid;
}
protected function submitButton_clickHandler(event:MouseEvent):void
{
if(validateForm(userInfoForm) == true)
{
//Alert.show("Proceed Genius!!!","Alert");
}
else
{
//Alert.show("Open ur eyes and fill the form properly u morron!!!","Morron");
}
}
]]>
</fx:Script>
<fx:Declarations>
<!--Below line can be used for XML from an external source-->
<!--<mx:HTTPService fault="errorHandler(event)" id="XMLService" resultFormat="e4x" url="formdata.xml" result="resultHandler(event)" />-->
</fx:Declarations>
<s:VGroup width="100%">
<s:Form id="userInfoForm" />
<s:Button label="Submit" id="submitButton" click="submitButton_clickHandler(event)"/>
</s:VGroup>
</s:View>

Resources