Handling form errors on Grails
I have not found clear information about how to deal with form errors on Grails so I made my own investigation.
How to deal with form field errors
We need to bear in mind that each field might have more than one error.
E.g.: Imagine a age field and we enter “abcde”. Having the right constraints, we’d display two error messages: “maximum 3 digits”, “only numbers please”.
In order to do this, Grails provide the following tags: renderErrors, hasErrors and eachError. This is well explained in the user guide.
How to print the list of messages using different formats
What if I don’t want to use the standard as=”list” which generates output?
This is an example of how to print error messages in a paragraph separated by<br/>
<g:hasErrors bean="${customer}" field="email">
<p>
<g:eachError bean="${customer}" field="email">
<g:message error="${it}" /><br/>
</g:eachError>
</p>
</g:hasErrors>
How to print global errors
I could not find a better way of doing this than through the standard Spring Errors interface:
Having a customer bean, in the controller:
customer.errors.reject("registration.data.access.error")
error()
And in the view:
<g:each var="error" in="${customer.errors.globalErrors}">
<g:message error="${error}" />
</g:each>