Tuesday, February 2, 2010

Custom Constraints

Grails constraints are short circuited when a field is declared nullable:true. This means if an attribute starts out nullable, say when the instance is in "Draft" status, but becomes required later, say when the user "Submits", the validator constraint can be used. Since validator takes a closure it can be invoked by reference or in-line. Or... pass arguments to make it more generic by wrapping the closure in a method like this:

    static Object requiredIfStatusEqual(status) {
// return a closure that will perform the validation
return {value, paf ->
// if the status is equal, the field is not required
if(status != paf.status) { return true }

// if the status is not equal, the value must be populated
return value ? true : 'default.blank.message'
}
}


Then, call the method in the static constraints block


static constraints = {
status( inList:[DRAFT, SUBMITTED])
shortTitle( validator:requiredIfStatusEqual(SUBMITTED))
}
- Ben Hidalgo

No comments:

Post a Comment