Displaying Grails Field Errors

后端 未结 2 1447
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-07 11:28

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

for each item with an error, I would like to print custom error messages

相关标签:
2条回答
  • 2021-02-07 12:12

    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)
       }
    }
    
    0 讨论(0)
  • 2021-02-07 12:33

    A somewhat simplier solution with a better performance would be;

    MessageSource messageSource //Inject the messageSource class
    
    e.errors.allErrors.each {
      String message = messageSource.getMessage(it, Locale.default)
    }
    

    OR

    If you want to deal only with field errors:

    e.errors.fieldErrors.each {
       String message = messageSource.getMessage("modified.invalid.validator.message", [it.field, 'message'] as Object[], Locale.default))
    }
    

    Where modified.invalid.validator.message is the local string in your messages.properties. In this particular example, this message reads something like...

    modified.invalid.validator.message=Property [{0}] of [{1}] does not pass validation
    
    0 讨论(0)
提交回复
热议问题