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.
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>
// 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With