Search code examples
grailserror-handlinggrails-ormgrails-controllerflash-message

Grails - custom Flash.message rendering


I am running a query to check if an entity id exists for multiple account ids. If the result set is not null, then I need to either throw an error or display a flash message.

The code for the method is as below:

def save() {

    def SAMLInfoInstance = new SAMLInfo(params)

    def account = Account.get(params?.accountId)        
    SAMLInfoInstance.setAccount(account)

    def samlInfoInstanceList = SAMLInfo.executeQuery("from SAMLInfo " +
        " where account.id <> ? " +
           " and entityId =  ?", [SAMLInfoInstance.accountId, SAMLInfoInstance.entityId])

    if (samlInfoInstanceList?.size > 0){
        flash.message = message(code: 'test.not.created.message', args: [message(code: 'SAMLInfo.label', default: 'SAMLInfo'), SAMLInfoInstance.entityId])
        /*flash.message = "default.not.created.message"
        flash.args = ["SAMLInfo", SAMLInfoInstance.entityId]
        flash.default = "SAMLInfo cannot be created"
        */
        render(view: "create", model: [SAMLInfoInstance: SAMLInfoInstance])
        return
        }

    if (!SAMLInfoInstance.save(flush: true)) {
        render(view: "create", model: [SAMLInfoInstance: SAMLInfoInstance])
        return
    }

    flash.message = message(code: 'default.created.message', args: [message(code: 'SAMLInfo.label', default: 'SAMLInfo'), SAMLInfoInstance.entityId])
    redirect(action: "list", id: SAMLInfoInstance.account.id)
}

In my view I render the flash message and the errors in the following manner:

<g:if test="${flash.message}">
        <br/>
        <div class="message" role="status">
        <g:message code="${flash.message}" args="${flash.args}" default="${flash.default}"/>
        </div>
        <br/>
        </g:if>
        <br/>

        <g:renderErrors bean="${SAMLInfoInstance}" as="list" />

In my message.properties file, I have the following line:

test.not.created.message=The SP url {1} is not allowed for this account. Please enter a different value.

When I run this code, the flash message displays as the string I pass as message i.e. "test.not.created.message". Also, this string is passed on to display whenever I navigate to any other page which displays flash.message. I am new to grails and groovy and would appreciate any help with this.

Thanks!


Solution

  • 2 problems then:

    1 - the message is not being retrieved from your message.properties:

    You must have other message.properties files in your project. Give it a check. Because if it's not found, grails shows the code itself instead of the message, since it did not find one. Maybe it's looking for your message in some other properties file, like the one specific for your Locale (ex: pt_BR or en_US). Other than that, you're doing it right using the message(code:...) construct.

    2 - Your flash message doesn't disappear:

    Instead of flash.message, use request.message.