0
votes

I'm having a problem while trying to validate and save domain object.

First I'm making the validation, when the validation is wrong, I'm putting error inside my future to be saved object, like this:

myDomain.errors.reject("An Error")
myDomain.discard()

Then, when I'm trying to save this object, I can see that error list has one error but 'validate()' returns 'true', also, when the function is finished the object is being saved automatically. I must say that all the called functions are in the same class which is a controller.

I need to know how to code my save function (in the controller class) which shows only the error without saving the object, and when the validation is good, to save the object.

Thanks!

2

2 Answers

0
votes

myDomain.validate() will overwrite myDomain.errors clearing the reject(). You could do something like this:

  // bind etc.
  ...

  // do grails validation
  if (!myDomain.validate()) {
    myDomain.discard()
  }

  // do custom validation
  if (custom validation has errors) {
    myDomain.errors.reject ()
    myDomain.discard()
  }

If you can move you custom validation into a validator on myDomain you do not need the custom validation.

You don't need to call save() explicitly.

0
votes

The fix was to use:

@Transactional(readOnly = true)

For the function which located in the service file. It makes the function to avoid from saving transactions in the end of it, which caused the problem in the first place.