2013-01-11 68 views
7

我是Grails新手,对于大多数人来说,我有一个问题应该很容易。grails - 显示flash消息

我有一个页面显示一个object列表。如果在删除object时出现DataIntegrityViolation,我想显示一条消息。我在做什么是:

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 
    } 
} 

这里是应显示提示信息:

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

对不起 - 我知道这是一个愚蠢的问题,但我真的不能找到解决方案。

+0

什么问题?看起来代码是正确的,如果DataIntegrityViolationException被捕获,你会看到“一些消息”字符串。 –

+0

问题是我看不到它 – sara

+0

我现在看到。你在谈论风格。有点误解(= –

回答

18

flash对象是Map,它存储了键/值对,因此您可以为错误消息定义自己的密钥。例如:

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) 

然后你可以检查包含errorflash对象,并使用不同风格的那种消息:

<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> 
+0

如何在不重定向的情况下显示消息?基本上我不想重定向到列表,因为在那里我重新加载对象列表,如果我不删除任何东西,我不需要重新加载。 – sara

+1

除非您通过Ajax提交请求,否则不能在没有浏览器重新加载(服务器重定向/转发)的情况下修改客户端数据。 – Gregg

1

严格的回答:只要时间回复您(或呈现与模型图)

为您的控制器:

def delete() { 

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

您的GSP:

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

但格雷格是对的,你应该永远没有一个redirect修改客户端的数据。 如果这样做,用户可能会刷新(或返回)相同的URL,并且意外再次尝试同样的操作。你应该真的喜欢hitt5的答案。

3

这可以帮助你:

def delete() { 
    def instanceToDelete= Myobject.get(params.id) 
    try { 
     instanceToDelete.delete(flush: true) 
     flash.success = "Object deleted correctly" 
    } catch (DataIntegrityViolationException e) { 
     flash.error = "Something goes wrong" 
    } 
    redirect(action: "list", id: params.id) 
} 

重定向到普惠制后,所有的代码,如果有错误或一切顺利到可以存储。

您可以将消息放在不同的变量中以区分错误和成功。

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