显示Grails字段错误 [英] Displaying Grails Field Errors

查看:103
本文介绍了显示Grails字段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人知道如何在下面的例子中打印出 fieldError

Does anybody know how I could get the fieldError to print out in the example below.

项目有错误,我想打印我在messages.properties文件中定义的自定义错误消息

for each item with an error, I would like to print custom error messages that I have defined in the messages.properties file

目前,这是打印默认错误代码

at the moment all this does is print the default error codes

item.errors?.allErrors?.each{ 
  println it.toString() 
}

我已经看过其他示例,您可以在其中查找字段的错误代码,例如

I have seen other examples where you can lookup an error code for a field e.g.

it.getFieldError('title').code

,但我想将默认消息转换为我的新错误消息并打印出来。

but I would like to convert the default message into my new error message and print that.

推荐答案

您需要访问messageSource bean,例如与

You need access to the messageSource bean, e.g. with

def messageSource

在您的控制器或服务。然后,您可以使用

in your controller or service. Then you can access the messages with

def locale = Locale.getDefault()
for (fieldErrors in bean.errors) {
   for (error in fieldErrors.allErrors) {
      String message = messageSource.getMessage(error, locale)
   }
}

这篇关于显示Grails字段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆