如何在flex中动态生成表单(<mx:form>)?</mx:form>

时间:2009-03-10 05:28:31

标签: flex

我需要从我从httpservice获取的xml文件生成一个mx:form。

此外,我需要预先填写表单中的数据。

有人可以给我一个示例代码吗?

3 个答案:

答案 0 :(得分:3)

显然你必须对此进行扩展,但这就是我如何构建动态表单..

            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);
        }

答案 1 :(得分:0)

检查一下:{3}}适用于Flex 3. HTH。

答案 2 :(得分:0)

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