Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Grails, how do I display validation error messages next to the fields?

The Grails 2.0.4 documentation for validation shows you how to display error messages at the top of the page and how to add a css class to an element if a field is invalid, but it doesn't tell you how to display the error message next to the fields themselves, something like this:

      -----------------------
Name: |                     |  You must enter a name!
      -----------------------

How do you retrieve the specific error message for an invalid field and then display it next to the field it's for?

like image 547
Daniel T. Avatar asked Jun 08 '12 05:06

Daniel T.


1 Answers

Actually, the documentation does show how to do this, it just isn't overly clear that this is what they mean:

<g:renderErrors bean="${book}" as="list" field="title"/>

If you specify the field attribute, it will only render error(s) for that field. So then it is just up to you to write the HTML accordingly.

<input type="text" ... /> <g:if test="${bean.hasErrors}"><g:renderErrors bean="${book}" as="list" field="title"/></g:if>

It can get as simple or as complicated as you would like it and while I generally like grails plugins, this just seems simple enough to do without one and you have more control over the markup.

like image 189
Gregg Avatar answered Oct 12 '22 02:10

Gregg