Aug 222010
 

Out the box Grails provides two ways to display messages to the user.

Just inside the body div at the top of each gsp view:

        <div class="body">
            <h1>Create Book</h1>
            <g:if test="${flash.message}">
                <div class="message">${flash.message}</div>
            </g:if>
            <g:hasErrors bean="${bookInstance}">
                <div class="errors">
                    <g:renderErrors bean="${bookInstance}" as="list" />
                </div>
            </g:hasErrors>

So we can place messages in flash scope and errors are automatically added to the bookInstance in the case of a failed data binding or save.

We can add errors to the instance if we have an instance.
But if we don’t have an instance then we need something like this:

Create a template gsp in grails-app/views/shared/_messages.gsp:

<g:if test="${flash.message}">
    <div class="message">${flash.message}</div>
</g:if>
<g:if test="${flash.warning}">
    <div class="message_error">${flash.warning}</div>
</g:if>

Some css just under the original messages entry in main.css:

.message_error {
    background: #fff3f3 url(../images/skin/exclamation.png) 8px 50% no-repeat;
    border: 1px solid red;
    color: #cc0000;
    margin: 10px 0 5px 0;
    padding: 5px 5px 5px 0px
}

Then at the top of our gsp views change to something like:

        <div class="body">
            <g:render template="/shared/messages" />
            <g:hasErrors bean="${assetInstance}">
            <div class="errors">
                <g:renderErrors bean="${assetInstance}" as="list" />
            </div>

Install and change the templates with ‘grails install-templates’ and edit them if you’d like all future generated gsp’s to use the shared messages template.

[suffusion-the-author display='first-name'] [suffusion-the-author display='last-name']:


Thank you for visiting.
Do look around.
Do leave a comment.

  5 Responses to “Displaying error messages in Grails”

  1. Displaying error messages in Grails…

    Out the box Grails provides two ways to display messages to the user.

    Just inside the body div at the top of each gsp view:

    Create Book

    ${flash.message}

  2. I’ve found it useful to use a parameterless `hasErrors` tag, and then include my command object in the model anytime I have an error. This removes the need for an extra chunk of code in every view.

    • No worries mate, you commented on the Grails Service and Controller Interface post too ๐Ÿ™‚ Your comments are welcome. Yes, at the time of writing Grails command objects had several limitations. Provided your method allows for the styling you need.

  3. Whoops, just realized this is a 4-year-old post about Grails v1! Cheers.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)