I'd like to know how to add a custom error to the hasErrors method so that the gsp picks up the error. My code thus far.
def recoverySetup = new RecoverySetup(params)
def onesolOrgkey = OnesolOrgkeyInfo.get(new OnesolOrgkeyInfo(params));
if(onesolOrgkey != null) {
recoverySetup.setOneSolOrgkey(onesolOrgkey)
} else {
recoverySetup.errors.reject('orgkey', 'You must provide a valid Org Key')
}
recoverySetup.validate()
if(recoverySetup.hasErrors()) {
render view: 'create', model: [recoverySetupInstance: recoverySetup]
return
}
As Danilo says, you probably want to add a constraint to your domain class to do that for you.
Learn more about constraints in http://grails.github.io/grails-doc/2.2.x/guide/single.html#constraints and http://grails.github.io/grails-doc/2.2.x/ref/Constraints/Usage.html .
If for whatever reason you really want to add a custom error that cannot be covered by the constraints (I can't imagine a case right now, but that doesn't mean it doesn't exists :-), you can still do it in a very similar fashion of what you posted:
instance.errors.rejectValue(fieldName, errorCode, message, defaultMessage)
instance.errors.reject(errorCode, message, defaultMessage)
The first rejects a concrete field, the second the bean in general. But bear in mind this errors will be reset when you invoke validate
again.
Also, you can display the errors of a bean automatically in grails with:
<g:hasErrors bean="${instance}">
<g:renderErrors bean="${instance}" />
</g:hasErrors>
See all the options here: https://grails.github.io/grails-doc/2.2.x/ref/Tags/hasErrors.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With