2

Obviously simplified, but I'm attempting to build a string which I would pass into another messages.properties entry. For example, maybe I had entries that looked like this:

someField.sillyError.good=good
someField.sillyError.bad=bad
someField.validation.error=This has been a [{3}] morning

With validation that looked like this:

static constraints = {
    someField(nullable: false, blank: false, validator: { val, obj ->
        def someOtherEntry = g.message(code: 'someField.sillyError.' + val)
        return ['someField.validation.error', someOtherEntry]
    }
 }

The call to g.message() doesn't work, and I can't seem to use anything else to get it either.

  • Possible duplicate : http://stackoverflow.com/questions/2814771/grails-getting-a-message-value-from-controller – Kelly Jul 26 '12 at 00:50

2 Answers2

1

I have similar situation and I use following code.

default.mandatory.message={0} is Mandatory
item.error.message=Item #{0} - {1}



public setItemFieldMandatoryError(FormXItem item, String field, String defaultMessage) {
    def messageSource = Holders.applicationContext.messageSource
    def errorMessage = messageSource.getMessage("default.mandatory.message", [field] as Object[], LocaleContextHolder.getLocale())
    item.errors.rejectValue(field, "formXItem.error.message", [formxItem.itemNumber, errorMessage] as Object[], defaultMessage)
}
Aram Arabyan
  • 2,339
  • 1
  • 17
  • 30
0

I was able to accomplish what I was hoping for by doing the following:

In messages.properties:

someField.sillyError.good=good
someField.sillyError.bad=bad
someField.validation.error=This has been a [{3}] morning

In someCommand:

def messageSource
static constraints = {
    someField(nullable: false, blank: false, validator: { val, obj ->
        def someOtherEntry = obj.messageSource.getMessage('someField.sillyError' + val, null, Locale.ENGLISH)
        return ['someField.validation.error', someOtherEntry]
    }
 }

You can inject the bean at the command object level, and then just call it from the obj variable within constraints. Came from a co-worker, so I can't take credit :P