Grails data binding - command objects with Lists

白昼怎懂夜的黑 提交于 2019-11-30 06:49:56

问题


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


回答1:


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



回答2:


Since Groovy 1.8.7 the List interface has a method called withLazyDefault that can be used instead of apache commons ListUtils:

List<Unit> units = [].withLazyDefault { new Unit() }

This creates a new Unit instance every time units is accessed with a non-existent index.

See the documentation of withLazyDefault for more details. I also wrote a small blog post about this a few days ago.



来源:https://stackoverflow.com/questions/9709864/grails-data-binding-command-objects-with-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!