yecid
yecid

Reputation: 180

How to use the validate() grails method without saving?

I have a problem with the validate() grails method, when I use entity.validate() the entity object is persisted on the database, but I require validate multiple objects before to save the data.

def myAction = {
  def e1 = new Entity(params)
  def ne1 = new EntityTwo(params)

  // Here is the problem
  // If e1 is valid and ne1 is invalid, the e1 object is persisted on the DataBase
  // then I need that none object has saved, but it ocurred. Only if both are success 
  // the transaction should be tried
  if(e1.validate() && ne1.validate()){
    e1.save()
    ne1.save()
    def entCombine = new EntityCombined()
    entCombine.entity = e1
    entCombine.entityTwo = ne1
    entCombine.save()
  }
}

My problem is that I do not want the objects to be saved before both validations are successful.

Upvotes: 0

Views: 1435

Answers (2)

yecid
yecid

Reputation: 180

I found a solution with withTransaction() method, because the discard() method is applied only to update cases.

def e1 = new Entity(params)
def ne1 = new EntityTwo(params)

Entity.withTransaction { status ->  
  if(e1.validate() && ne1.validate()){
    e1.save()
    ne1.save()
    def entCombine = new EntityCombined()
    entCombine.entity = e1
    entCombine.entityTwo = ne1
    entCombine.save()
  }else{
    status.setRollbackOnly()
  }
}

So the transaction is completed only if the validation is successfully, by other way the transaction is rolled back.

I wait that this info can be to help for any people. Regards to all! :) YPRA

Upvotes: 0

Burt Beckwith
Burt Beckwith

Reputation: 75671

Call discard() on any instance don't want to be automatically persisted when it's detected as changed/dirty:

if (e1.validate() && ne1.validate()){
   ...
}
else {
   e1.discard()
   ne1.discard()
}

Upvotes: 4

Related Questions