Reputation: 1781
I have a validating command object in my controller method and when validation fails I want to print out the error message rendered as JSON:
def doSomething(MyCommand cmd) {
if (cmd.hasErrors()) {
render ([success: false, error: cmd.errors.getFieldError("myfield")] as JSON)
}
}
This prints the JSON representation of the field error, but I just want to print the resolved error message. How can I achieve that?
Thanks!
Upvotes: 2
Views: 6914
Reputation: 749
The post is old, but here is my solution.
import org.codehaus.groovy.grails.commons.ApplicationHolder
def myCommand = new MyCommand()
myCommand.errors.reject('Foo error')
myCommand.errors.reject('Bar message')
myCommand.errors.reject('myCommand.myfield.nullable')
def appHolder = ApplicationHolder.application.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')
def list = myCommand.errors.allErrors.collect{appHolder.g.message([error: it])}
list
Result:
["Foo error","Bar message","Property myfield cannot be null"]
Upvotes: 1
Reputation: 4980
This works for me
def errMsgList = domainClassObj.errors.allErrors.collect{g.message([error : it])}
Upvotes: 3
Reputation: 1781
Ah, I resolved this problem:
render ([success: false, error: message(error: cmd.errors.getFieldError("myfield"))] as JSON)
Before, I got an error using message(), maybe I had made another mistake then.
Upvotes: 3