Search code examples
grailsgroovycommand-objects

Grails command objects and input name values


I have a form where I have to have the input elements ordered specifically. So my form looks something like this:

<input type="text" name="name"/>
<select name="contacts.first">...</select>
<select name="contacts.second">...</select>
...

I have a command object that I'm trying to use to validate this form. However, I can't seem to get it to map correctly. My command object looks like this:

@Validatable
class MyCommand {
     def name
     def contacts

     static constraints = { /* ... */ }
}

My controller action looks like:

def update = { MyCommand cmd -> 
    if (cmd.validate()) {
         /* ... */
    }
}

When I look at cmd.contacts, it's null. If I name each select just contacts instead of contacts.first, it is an array of values as expected, but I did not want to depend on the browser to make sure these items are in a specific order. Any suggestions to making this work? The correct order is crucial.


Solution

  • Original idea: http://stateyourbizness.blogspot.com/2009/02/binding-to-collection-fields-on-command.html

    So for your command object you could use:

    import org.apache.commons.collections.FactoryUtils;
    import org.apache.commons.collections.ListUtils;
    
    class MyCommand {
        def name
        List contacts = ListUtils.lazyList([], FactoryUtils.constantFactory(''))
        /* ... */
    }
    

    And have your html look like:

    <input type="text" name="name"/>
    <select name="contacts[0]">...</select>
    <select name="contacts[1]">...</select>