grails CommandObject静默绑定

时间:2013-06-13 14:03:34

标签: grails

有没有办法只绑定命令对象上存在的属性?一般的概念是,我在地图中有很多不同的参数,我不想明确地说出来。

例如,给定地图

 def map = ['first': "Nick", 'last': "Capito", 'isRegistered': false ]


@grails.validation.Validateable
class EditCommand{
     String first
     String last 
}

def edit{ EditCommand command ->

}

会崩溃,并抛出错误Message: No such property: isRegistered for class: EditCommand

我一直在手动做。

new EditCommand(params.findAll{['first', 'last'].grep(it.key)})

2 个答案:

答案 0 :(得分:3)

使用我评论中提到的bindData,在您的特定情况下,它将类似于

def edit = {->
    def cmd = new EditCommand()
    bindData(cmd, map, [exclude: ['isRegistered']])
    .......
}

如果你不想排除params,你可以默认include来自命令对象的所有字段。通过这样做,您可以得到主要问题的答案

有没有办法只绑定命令对象上存在的属性
是的,这是如何做到的..

def edit = {->
    def cmd = new EditCommand()
    //This has all the fields which is present in the Command Object
    //Others will be excluded by default
    def includedFields = 
            cmd.class.declaredFields.collectMany{!it.synthetic ? [it.name] : []}
    bindData(cmd, map, [include: includedFields])
    .......
}

答案 1 :(得分:0)

如果您更改视图以使地图/实例代表您的命令对象而不是顶级参数图,则可以干净利落地实现:

视图:

<g:textField name="editCommand.first" value="${editCommand.first}" />

控制器:

def edit(@RequestParameter('editCommand') EditCommand editCommand) {
    if (params.boolean('isRegistered'))
        // etc.
}

或者您可以手动创建实例:

def edit() {
    EditCommand command = new EditCommand(params.editCommand)
    if (params.boolean('isRegistered'))
        // etc.
}