I am having hard time getting hasErrors to work with index开发者_JAVA百科ed properties. For example
class Order {
String prop1
String prop2
static hasMany = [items: Item]
}
class Item {
String name
static constraints = {
name(blank:false)
}
}
Validation works properly and on item.name being blank I do get an error with
<g:renderErrors bean="${orderInstance}"/>
However, I am trying to have input box highlighted using hasErrors :
<g:each in="${orderIntsance.items}" status="i" var="item">
<span class="field ${hasErrors(bean: orderInstance, field: ????????? , 'errors')}">
<g:textField name="items[${i}].name" value="${item?.name}"/>
</span>
</g:each>
Not sure how to get to it with a field: property, any ideas?
Thanks
Found it, got to implement a custom validator per Grails Validation doc page (duh):
"In some situations (unusual situations), you might need to know how to transfer an error from a nested child object to a parent domain object. In some circumstances, if you validate the children objects before the parent object, then the errors on the children objects will get reset before the object is sent to the JSP." (http://www.grails.org/Validation)
static constraints = {
children( nullable:true, validator: {val, obj, errors ->
def errorFound = false;
val.each{ child ->
if(!child .validate()){
errorFound = true;
child .errors.allErrors.each{ error->
obj.errors.rejectValue('children', "parent.child.invalid",
[child, error.getField(), error.getRejectedValue()] as Object[],
"For source [${child}],
field [${error.getField()}] with value [${error.getRejectedValue()}] is invalid.")
}
}
}
if(errorFound) return false;
})
}
I had a similar requirement and tried the following way and it worked. Just wanted to share it
${hasErrors(bean: orderInstance, field: 'items['+ i +'].name', 'errors')
精彩评论