I am trying to use Grails Command Object to filter action parameters. But I want to set a default value if the parameter is not present in 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.
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'
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.