Solved

Dynamic Form Creation Flex

Posted on 2008-06-20
3
5,002 Views
Last Modified: 2010-04-21
Hi Genusies,
I have XML file which have a format like
<name>robert</name>
<last name>jackson</last name>

Now I have to create a dynamic form in Flex which contains form items called name with value "robert"
lastname "jackson".
This form has to be created at runtime so that in case in future if xml xhanges so does the form.

I am still a newbie in flex :)

Thanks in advance for replying to my post.

Thanks,
dojjol


0
Comment
Question by:dojjol
3 Comments
 
LVL 13

Accepted Solution

by:
bglodde earned 500 total points
Comment Utility
Your XML will have to increase in complexity to do this correctly. See the attached starter code/template that demonstrates how you can both generically and dynamically create form elements from XML in Flex. Please also note this is only one way to do it - I'm sure there are many others.

Hope that helps you get started.
- XML FILE (save as test/formdata.xml) - 
 

<?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 App -
 

<?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>

Open in new window

0
 

Author Closing Comment

by:dojjol
Comment Utility
Thanks
0
 

Expert Comment

by:PLouis74
Comment Utility
This is awesome and is perfectly in line with something i was trying to accomplish!!!

i modified this to also allow for method names and dataproviders for form items like comboBox, etc.
NEW XML-------------
<?xml version="1.0"?>
<userinfoform>
        <user>
                <firstname inputtype="TextInput" formlabel="First Name">Robert</firstname>
                <lastname inputtype="TextInput" formlabel="Last Name">Jackson</lastname>
                <venueitems inputtype="ComboBox" formlabel="Venue" dataprovider="venueDataSet" methodname="comboBoxHandler"></venueitems>
                <submitbutton inputtype="Button" buttonlabel="Send Form" methodname="handleFormSubmit"></submitbutton>
        </user>
</userinfoform>


MXML----------------

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="handleCreationComplete()">
        <mx:Script>
        <![CDATA[
	    	import mx.controls.ComboBox;
	    	import mx.collections.ArrayCollection;
	    	import mx.controls.Button;
	        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;
	        
	        public var venueDataSet:ArrayCollection = new ArrayCollection();
	        public var labelList:Array = new Array("New York", "Orlando", "Cincinnati");
	        public var dataList:Array = new Array("NY", "OL", "CN");
	        
	        private function initDataSet():void
	        {
				for (var i:int = 0; i < dataList.length; i++){
					var newItem:Object = new Object();
					newItem.data = dataList[i];
					newItem.label = labelList[i];
					  
					venueDataSet.addItem(newItem);
				}
			}
	
	        
	        private function handleCreationComplete():void
	        {
	                initDataSet();
	                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 comboBoxHandler( e:Event ):void
	        {
	        	var cBox:ComboBox = e.currentTarget as ComboBox;
	            trace( "You selected: " +  cBox.selectedItem.label );
	            trace( "Data: " +  cBox.selectedItem.data );
	        }
	                
	        private function handleFormSubmit( e:MouseEvent ):void
	        {
				trace( "You clicked the submit button!!!" );	
	        }
	        
	        private function buildForm(xml:XML):void
	        {
	            var lst:XMLList = xml.children();
	            var frmItem:FormItem;
	            var txtInput:TextInput;
	            var btItem:Button;
	            var cBox:ComboBox;
	            var itemMethod:Function;
	                    
	            for(var i:int = 0; i < lst.length(); i++){
	                var x:XMLList = lst[i].children();
	                
	                for(var a:int = 0; a < x.length(); a++){
	                    if(x[a].@inputtype == 'TextInput'){
	                        frmItem = new FormItem();
	                        frmItem.direction = "horizontal";
	                        frmItem.label = x[a].@formlabel;
	                        
	                        txtInput = new TextInput();
	                        txtInput.text = x[a];
	                        frmItem.addChild(txtInput);
	                        
	                    }else if(x[a].@inputtype == 'Button'){
							frmItem  = new FormItem();
	                        frmItem.direction = "horizontal";
	                        frmItem.label = x[a].@formlabel;
	                        
	                       	btItem = new Button();
	                        btItem.label = x[a].@buttonlabel;
	                        itemMethod = this[ x[a].@methodname ] as Function;
	                        btItem.addEventListener(MouseEvent.CLICK, itemMethod);
	                        frmItem.addChild(btItem);
	                                               
	                    }else if(x[a].@inputtype == 'ComboBox'){
	                    	frmItem  = new FormItem();
	                        frmItem.direction = "horizontal";
	                        frmItem.label = x[a].@formlabel;
	                        
	                        cBox = new ComboBox();
	                        itemMethod = this[ x[a].@methodname ] as Function;
	                        cBox.dataProvider = this[ x[a].@dataprovider ] as ArrayCollection;
	                        cBox.addEventListener(Event.CHANGE, itemMethod);
	                        frmItem.addChild(cBox);
	                    	
	                    }else{
	                    	// Support other form field types
	                    	                    	
	                    }
	                    
	                    userInfoForm.addChild(frmItem);
	                    
	                }
	            }
	        }
	                
	    ]]>
        </mx:Script>
        <mx:HTTPService fault="errorHandler(event)" id="XMLService" resultFormat="e4x" url="assets/form_1.xml" result="resultHandler(event)" />
        <mx:Form id="userInfoForm" />
</mx:Application>

Open in new window

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

First things first - Preparation We need all the part for this install and it's much nicer to have them all on hand when you need them so here's what's required. Download Eclipse 3.5 32 bit (I like the Classic flavour) from here. (http://www.e…
Find out what Office 365 Transport Rules are, how they work and their limitations managing Office 365 signatures.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now