Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grails add validation error to hasErrors

Tags:

grails

groovy

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
}
like image 857
Code Junkie Avatar asked Jul 30 '15 19:07

Code Junkie


1 Answers

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

like image 128
Deigote Avatar answered Oct 21 '22 07:10

Deigote