Search code examples
grailsgrails-controller

Grails data binding - command objects with Lists


Grails 1.3.7

Trouble with data binding Command objects that have List content. Example Command:

class Tracker {
    String name
    String description
    List<Unit> units = new ArrayList()
}

class Unit {
    String name
    Long unitMax
    Long unitMin
}

create GSP for Tracker has the Unit fields. One example:

<g:textField name="units[0].unitMax" value=""/>

TrackerController save method:

 def save = { Tracker trackerInstance ->
   trackerInstance = trackingService.saveOrUpdateTracker(trackerInstance)
 }

But, always java.lang.IndexOutOfBoundsException

Alternatively, if I update controller to:

def save = {
   Tracker trackerInstance = new Tracker()
   trackerInstance.properties = params
   ....

Then groovy.lang.ReadOnlyPropertyException: Cannot set readonly property: properties for class: com.redbrickhealth.dto.Tracker Any ideas?

There seems to be a difference between binding in GORM vs Command objects.

Maybe I need to extend and register a PropertyEditorSupport for Unit?

-Todd


Solution

  • Grails requires an command with existing list, that will be filled with data from reques.

    If you know exact number of units, say 3, you can:

    class Tracker {
        String name
        String description
        List<Unit> units = [new Unit(), new Unit(), new Unit()]
    }
    

    or use LazyList from apache commons collections

    import org.apache.commons.collections.ListUtils
    import org.apache.commons.collections.Factory
    class Tracker {
        String name
        String description
        List<Unit> units = ListUtils.lazyList([], {new Unit()} as Factory)
    }