Wednesday, June 18, 2008
Dynamically create a Flex form from XML
Recently, I was asked how to create forms dynamically and generically from XML in Flex. With a little experimentation with AS3 and the power of E4X :) - I was able to get the basics working with minimal coupling to the XML file (as much as possible anyway).
XML File:
<?xml version="1.0"?> <userinfoform> <user> <firstname inputtype="TextInput" formlabel="First Name">Robert</firstname> <lastname inputtype="TextInput" formlabel="Last Name">Jackson</lastname> </user> </userinfoform>
MXML File:
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="handleCreationComplete()"> <mx:Script> <![CDATA[ import mx.containers.FormItem; import mx.controls.Label; import mx.controls.TextInput; import mx.controls.Alert; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; private function handleCreationComplete():void { XMLService.send(); } 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; var tb:TextInput = new TextInput(); tb.text = x[j]; frmItem.addChild(tb); userInfoForm.addChild(frmItem); } else { // Support other form field types } } } } ]]> </mx:Script> <mx:HTTPService fault="errorHandler(event)" id="XMLService" resultFormat="e4x" url="test/formdata.xml" result="resultHandler(event)" /> <mx:Form id="userInfoForm" /> </mx:Application> Supporting all of the available form types would get messy quickly, but perhaps this will serve as a good starting point for someone with a need to build forms dynamically.
MXML + XML sample
|