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.

One Comment

  1. grailstutorial.org says:

    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}

Leave a Reply

Spam protection by WP Captcha-Free