简体   繁体   English

Grails数据绑定

[英]Grails data binding

A Grails controller received is called with the following request parameters: 使用以下请求参数调用收到的Grails控制器:

defaultPrice[0].amount  22
defaultPrice[0].currency 1
defaultPrice[0].id  
defaultPrice[1].amount  33
defaultPrice[1].currency 3
defaultPrice[1].id  

I've defined the following command class: 我定义了以下命令类:

class PriceCommand {
    BigDecimal amount
    Integer currency
    Integer id
}

I attempt to bind the request parameters to a `List' in the action 我尝试在操作中将请求参数绑定到“列表”

def save = {List<PriceCommand> defaultPrice ->

}

But within the action, defaultPrice is null. 但是在操作中, defaultPrice为null。

It requires an command with existing list of data, with specified name, that will be filled with data from request. 它需要一个具有指定名称的现有数据列表的命令,该命令将填充来自请求的数据。

Try 尝试

import org.apache.commons.collections.ListUtils
import org.apache.commons.collections.Factory

class PriceListCommand {
   List<PriceCommand> defaultPrice = ListUtils.lazyList([], {new PriceCommand()} as Factory)
}

and use this command inside controller. 并在控制器中使用此命令。 It should works 应该可行

I'm not sure if this is what your looking but it may help... 我不确定这是否是您的外观,但可能会有所帮助...

1.) I think indexed params only work if you have a parent-child or one-to-many relationship. 1.)我认为只有当您有亲子关系或一对多关系时,索引参数才有效。 For example you might need to introduce a PriceCommandParent which contains a list of PriceCommand . 例如,您可能需要引入一个PriceCommandParent其中包含一系列PriceCommand I may be wrong on this and I welcome any corrections. 我对此可能是错的 ,我欢迎任何纠正。

2.) I've found that indexed params aren't as magically as some of the other areas of Grails/Groovy so sometimes i'd rather deal with the mapping myself. 2.)我发现索引参数不像Grails / Groovy的其他某些区域那样神奇,因此有时我宁愿自己处理映射。 Below is how i've handled it in the past.... 以下是我过去的处理方式...

def things = []

params.each{name, value->
    if (name.matches('^(thing\\[\\d+\\])$')){ //<-- look for 'thing[x]'
        things.add(new Thing(params[name]);
    }   
}

Let me know if any of this is of help 让我知道这是否有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM