Sunday, February 14, 2010

Grails partial validation of domain objects

I found this funky little feature in Grails the other day. Partial validation of domain objects. If you are fortunate enough to be developing an application that's domain model can be designed in a way that closely models your required screens (say a bunch of GRUD screens) then this feature will probably be of little interest to you. However if like me you are finding that the default Grails CRUD type approach is not flexible enough for your requirements check this out!

I am developing a web flow application that will populate a domain object (the user is filling in an application form) across multiple controllers and or actions. At each stage of the flow I am wanting to only validate the properties which the current action is charged with binding.

Lets say this is my domain object
class Application {

String firstName
String lastName
String emailAddress
Date dateOfBirth
String sex

String address1
String address2
String address3
String address4

//etc..

static constraints = {
firstName(blank:true)
lastName(blank:true)
emailAddress(email:true)
dateOfBirth(nullable:false)
sex(inList:["Male", "Female"])
address1(blank:false)
address2(blank:false)
address3(blank:false)
address4(blank:false)
}
}
I would like to populate this domain across three controller actions. To do this I just need to pass a map of property names to the "validate" method of the domain object. Yep, its as simple as that!
//...action1
applicationInstance.validate(['firstName', 'lastName', 'emailAddress'])

//...action2
applicationInstance.validate(['dateOfBirth', 'sex'])

//...action3
applicationInstance.validate(['address1', 'address2', 'address3', 'address4'])

No comments:

Post a Comment