Flex loop over form values (mx:Form, mx:FormItems)

I’ve been messing around with the FlexOnRails Cairngorm/WebORB app and wanted to add some more fields to the flex form for projects (I’m building a construction project tracker so I need to add the project’s address). However as I’m a lazy programmer I quickly got tired of typing all the values to be passed in the event dispatcher. Here’s the original code:

private function projectFormValues () : Object
{
    var values : Object = new Object();

    values.street_address = street_address.text;
    values.suite = suite.text;
    values.city = city.text;
    // etc...

    return values;
}

And below is my revised ‘projectFormValues’ method, it now loops over the form and gets all the values:

private function projectFormValues () : Object
{
    var values : Object = new Object();

    // get form items
    var formItems = project_form.getChildren();

    // loop items and add values
    for (var i = 0; i < formItems.length; i++)
    {
        // formItem
        var formItem = formItems[i].getChildren();
        values[formItem[0].name] = formItem[0].text;
    }

    return values;
}

The form just for reference…

<mx:Form height="100%" width="100%" id="project_form">
        <mx:FormItem label="Street Address:">
            <mx:TextInput id="street_address" text="{model.selectedProject.street_address}"/>
        </mx:FormItem>
        <mx:FormItem label="Suite:">
            <mx:TextInput id="suite" text="{model.selectedProject.suite}"/>
        </mx:FormItem>
        <mx:FormItem label="City:">
            <mx:TextInput id="city" text="{model.selectedProject.city}"/>
        </mx:FormItem>
        <!-- more form items... -->
    </mx:Form>

3 Comments

  1. Posted December 21, 2006 at 2:21 pm | Permalink

    Very nice and DRY. It would be nice if the Form component had a method to do this.

    Best,

    Derek

  2. Grover Fields
    Posted February 26, 2007 at 7:52 am | Permalink

    Good job but I am getting errors.

    1.) When no data is inserted into the form field
    2.) How do I submit the entire object to a CFC for data posting!

  3. MArcio
    Posted January 28, 2008 at 8:28 pm | Permalink

    Im Flex Builder 3 occurr error

    1008: variable ‘formItem’ has no type declaration.

    1008: variable ‘formItems’ has no type declaration.

    1008: variable ‘i’ has no type declaration.

    For i

    i using

    for( var i:int = 0; i < formItems.length; i++ ){

    And this ok

    How to resolve others ?

    Please you Helpe me

Post a Comment

Your email is never shared. Required fields are marked *

*
*

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word