【问题标题】:Grails data binding - command objects with ListsGrails 数据绑定 - 带有列表的命令对象
【发布时间】:2012-03-31 09:05:14
【问题描述】:

Grails 1.3.7

数据绑定存在 List 内容的 Command 对象的问题。示例命令:

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

class Unit {
    String name
    Long unitMax
    Long unitMin
}

为 Tracker 创建 GSP 具有 Unit 字段。一个例子:

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

TrackerController保存方法:

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

但是,总是 java.lang.IndexOutOfBoundsException

或者,如果我将控制器更新为:

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

然后 groovy.lang.ReadOnlyPropertyException:无法设置只读属性:类的属性:com.redbrickhealth.dto.Tracker 有任何想法吗?

GORM 与 Command 对象中的绑定似乎有所不同。

也许我需要为 Unit 扩展和注册 PropertyEditorSupport?

-托德

【问题讨论】:

    标签: grails grails-controller


    【解决方案1】:

    从 Groovy 1.8.7 开始,List 接口有一个名为 withLazyDefault 的方法,可以用来代替 apache commons ListUtils:

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

    这会在每次使用不存在的索引访问 units 时创建一个新的 Unit 实例。

    有关详细信息,请参阅documentation of withLazyDefault。几天前我还写了一个小blog post。

    【讨论】:

      【解决方案2】:

      Grails 需要一个具有现有列表的命令,该命令将填充来自请求的数据。

      如果您知道确切的单位数,例如 3,您可以:

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

      或使用 apache commons 集合中的 LazyList

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

      【讨论】:

        猜你喜欢
        • 2011-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-12
        • 2018-11-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多