2

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

例如,给定地图

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

2 回答 2

3

Using bindData as mentioned in my comment, in your particular case it will be something like

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

In case, you do not want to exclude params, you can by default include all fields from the command object. By doing this you get the answer to your main question

Is there a way to only bind the properties that exist on a command object?
Yes, here is how it can be done..

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])
    .......
}
于 2013-06-13T14:13:04.143 回答
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.
}
于 2013-06-13T17:33:45.843 回答