The excellent GORM Gotchas Series inspired me to write about a gotcha I found recently.
You have a domain class Container which contains elements:
class Container { static hasMany = [elements:Element] List<Element> elements }
and the element has a constraint:
class Element { static belongsTo = [container:Container] static constraints = { email(email: true) } String email }
When you try to save a container with more than one element that fails validation, only the first error appears:
Container c = new Container() c.addToElements(new Element(email: "a")) c.addToElements(new Element(email: "b")) c.save() assertEquals(2, c.errors.allErrors.size()) // fails, only one error is recorded!
The solution described in the docs coined with In some situations (unusual situations)) is to use a custom validator in the container class:
class Container { static constraints = { elements(validator: { List val, Container obj -> val.each {Element element -> if(! element.validate()) { element.errors.allErrors.each { error-> obj.errors.rejectValue( 'elements', error.getCode(), error.getArguments(), error.getDefaultMessage() ) } } } return true }) } static hasMany = [elements:Element] List<Element> elements }
Thanks for pointing that out. I ran into that same problem as you can see last paragraph here but decided to loop over each item in the list and validate it in my controller in order to get the complete list of validation errors. This seems like a cleaner way, I will give it a shot.