alexcuesta

My tech blog

Handling form errors on Grails

leave a comment »

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>

Written by alexcuesta

February 22, 2011 at 3:51 pm

Posted in Groovy/Grails

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: