user2782001
user2782001

Reputation: 3488

How to stop grails erasing custom validation errors

In my Grails app, I am using methods in a service to do complicated validation for user submitted data. Unfortunately, Grails is quietly sabotaging me.

  1. I populate the domain instance with the user submitted data

  2. I hand the instance off to the service, which analyzes the properties.

  3. If errors are found I add them using

      instance.errors.rejectValue('myValue','errors.customErrorCode','Error') 
    
  4. BEHIND THE SCENES, when the service passes the domain instance back to the controller grails checks for changed properties and calls validate() before returning the instance. (verifiable by seeing the beforeValidate event called on returning a domain instance from a service to a controller where one or more properties has changed)

  5. That behavior clears any custom errors I have added and the instance I get back in the controller is now incorrectly without error.

How can I

A) stop grails from validating between service and controller

OR

B) prevent a validate() call from wiping my custom errors.

EDIT So far I've found one partial answer,

If you use instance.get(params.id), grails will self validate behind the scenes wiping custom errors.

If you use instance.read(params.id) you can bypass this behavior to an extent.docs

But this solution is limited by domain relationships. Any other solutions welcome.

Upvotes: 0

Views: 337

Answers (2)

Matvei Nazaruk
Matvei Nazaruk

Reputation: 824

Seems that it is not custom validation. It can be because of transactional service. Service opens separate transaction for each method and clears entities after method end. You can find this mentioned in docs(read the last paragraph of part ). So errors dessappear not because of validation.

Don't know if your service is transactional. But if it is - you can add @NotTransactional annotation to method were you want not to loose errors. And errors will be saved.

Hope it helped, Matvei.

Upvotes: 1

z.eljayyo
z.eljayyo

Reputation: 1289

Not sure how your code looks like or what is causing the problem, but in any case I strongly suggest implementing custom validators in the domain class or in a command object within the constrains.

Here are some examples from grails docs: http://docs.grails.org/2.4.0/ref/Constraints/validator.html

Upvotes: 0

Related Questions