Does the following code run without an exception and what does the following code print out?
def isNull = null isNull += null println isNull.getClass()
Does the following code run without an exception and what does the following code print out?
def isNull = null isNull += null println isNull.getClass()
1 Comment |
2010, Author: Jens Lukowski, Groovy | Tagged: Gotcha, groovy |
Permalink
Posted by jenslukowski
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
}
2 Comments |
2010, Author: Jens Lukowski, Grails, Groovy | Tagged: Gotcha, grails, groovy |
Permalink
Posted by jenslukowski
| vasilikvockin on Communication Through Cod… | |
| David on Communication Through Cod… | |
| Miq on Communication Through Cod… | |
| Miq on Composite comparators in … | |
| Frisian on Composite comparators in … |
Theme: Customized Contempt by Vault9.
Blog at WordPress.com.