How can I apply defaults to a command object in Grails 2.3?
Note that I need to retrieve these defaults from a service when the corresponding url param is unspecified.
I have the following command object as the argument to my action
class SearchCommand {
int page
int pageSize // todo: get default from configurationService
String orderBy // todo: get default from configurationService
String search
}
I've looked at @BindUsing but it doesn't seem to be invoked when the corresponding request parameter is missing, defeating my attempt at applying a default value.
You could also do something like this:
A controller..
// grails-app/controllers/com/demo/DemoController.groovy
package com.demo
class DemoController {
def createPerson(Person p) {
render "First Name: ${p.firstName}, Last Name: ${p.lastName}"
}
}
class Person {
String firstName
String lastName
}
A service...
// grails-app/services/com/demo/MyConfigurationService.groovy
package com.demo
class MyConfigurationService {
def initializePerson(Person p) {
p.firstName = 'Default First Name'
p.lastName = 'Default Last Name'
}
}
A binding listener...
// src/groovy/com/demo/PersonBindingListener.groovy
package com.demo
import org.grails.databinding.events.DataBindingListenerAdapter
class PersonBindingListener extends DataBindingListenerAdapter {
def configService
Boolean beforeBinding(Object target, Object errors) {
configService.initializePerson target
true
}
boolean supports(Class<?> clazz) {
clazz == Person
}
}
Register the listener bean...
// grails-app/conf/spring/resources.groovy
beans = {
myListener(com.demo.PersonBindingListener) {
configService = ref('myConfigurationService')
}
}