Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grails - display flash message

Tags:

grails

I’m new to Grails, and I have a question that should be easy for most of you.

I have a page displaying an object list. I want to display a message if there’s a DataIntegrityViolation when an object is deleted. What I’m doing is:

def delete() {

    def instanceToDelete= Myobject.get(params.id)
    try {
        instanceToDelete.delete(flush: true)
        redirect(action: "list", id: params.id)
    }
    catch (DataIntegrityViolationException e) {
        flash.message = "some message"
        //I want to refresh the div containing the flash.message here
    }
}

Here is where the flash message should be displayed:

  <g:if test="${flash.message}">
  <div class="alert alert-error" style="display: block">${flash.message}</div>

Sorry — I know it’s a silly question, but I really can't find a solution.

like image 582
sara Avatar asked Jan 11 '13 11:01

sara


2 Answers

The flash object is a Map which stores key/value pairs, so you can define your own key for error messages. For example:

try {
    instanceToDelete.delete(flush: true)            
    flash.message = "successfully deleted object"
 }
 catch (DataIntegrityViolationException e) {
    flash.error = "could not delete object"            
 }
redirect(action: "list", id: params.id)

Then you can check the flash object containing the error key, and use a different style for that kind of message:

<g:if test="${flash.error}">
  <div class="alert alert-error" style="display: block">${flash.error}</div>
</g:if>
<g:if test="${flash.message}">
  <div class="message" style="display: block">${flash.message}</div>
</g:if>
like image 139
hitty5 Avatar answered Oct 15 '22 01:10

hitty5


// backend code example

def save () { 
    if(params.name) { 
          . 
          . 
      object.save(); 
      flash.message =  "Saved successfully" 
    } 
    else { 
        flash.message = "Saved fail"
    }

// HTML example

<g:if test="${flash.message}">
   <div class="update_message" role="status">${flash.message}</div>
</g:if>
like image 42
Asif Avatar answered Oct 15 '22 01:10

Asif