简体   繁体   English

Grails命令对象默认值

[英]Grails Command Object Default Value

I am trying to use Grails Command Object to filter action parameters. 我正在尝试使用Grails命令对象来过滤动作参数。 But I want to set a default value if the parameter is not present in URL. 但是,如果该参数不在URL中,我想设置一个默认值。

class ListCommand {

    String order = 'desc'
    String sort = 'startDate'

}

def list(ListCommand cmd) {
    println cmd.order
}

I thought the behaviour would be same as if I was creating a domain object. 我以为行为与创建域对象相同。 I don't want to handle each parameter in the action like: 我不想像这样处理动作中的每个参数:

cmd.order = params.order ?: 'desc'

if you always use such action declarations: 如果您始终使用这样的动作声明:

def list(ListCommand cmd) { ... }

or 要么

def list = {ListCommand cmd -> ...}

you may try this: 您可以尝试以下方法:

class ListCommand {
    String order
    String sort

    def beforeValidate() {
        order = order ?: 'desc'
        sort = sort ?: 'startDate'
    }
}

because in those action definitions validate() method always calls for command objects. 因为在这些动作定义中validate()方法总是调用命令对象。

I don't think you can set default values to command object fields. 我认为您不能为命令对象字段设置默认值。

I suggest that you create a service to initialize your command object with default values before binding your params: 我建议您在绑定参数之前创建一个服务以默认值初始化命令对象:

def service

def action = {
    def listCommand = service.createListCommand() 
    bindData(listCommand, params)
}


class Service {
   def createListCommand() {
       def listCommand  = new ListCommand()
       initDefaultValues(listCommand)
       return listCommand
   }

def initDefaultValues(def listCommand){
        listCommand.order = 'desc'
        listCommand.sort = 'startDate'
    }
}

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

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