Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails nested domains - addAll errors to top level domain object

I have a Grails domain like this:

class User {
....
Address address
}

While saving the user, I want to validate the Address object as well and add all errors of Address object to the User object itself.

I am trying to write a custom validator wherein I do it.validate(), but I am not able to find a way to "addAll" the error messages of address.

like image 939
Manish Avatar asked Oct 23 '11 16:10

Manish


2 Answers

This discussion below on the grails mailing list about calling validation on child objects and appends them to a single errors list that might work for you.

Form validation with children

If Address has static belongsTo = [user:User] then calling User.validate() or User.save() should also call validation on Address. I've not tried collecting errors on a child object into the parent object's errors list, but for a simple one-to-one association you may not need to, and simply display the errors something like this:

<g:if test="${user?.hasErrors() || user.address?.hasErrors()}">
  <div class="errors">
    <g:hasErrors bean="${user}">
       <g:renderErrors bean="${user}" as="list" />
    </g:hasErrors>
    <g:hasErrors bean="${user?.address}">
       <g:renderErrors bean="${user?.address}" as="list" />
    </g:hasErrors>
  </div>
</g:if>
like image 151
R. Valbuena Avatar answered Nov 11 '22 18:11

R. Valbuena


Since this is probably a frontend related task, I would not try to fiddle with those error classes. I advance you to just call the validate function within the custom validator like this:

address(validator: { val, obj ->
   val?.validate();
});

In the GUI you will find your error messages for the nested domain class within the instance of the nested domain class. Therefore you need to pass the domain class to the GSP.

<g:renderErrors bean="${address}" field="street" />

However if you really want to get a new collection having all errors inside of all nested classes you can have a look at the plugin http://www.grails.org/plugin/extended-validation. With this plugin you have an additional error set, which contains all error messages of nested domain classes (if it is configured to do like this):

user.allErrorsRecursive()

But to be honest, I have not tested it yet ;)

like image 22
Chris Avatar answered Nov 11 '22 17:11

Chris