views:

99

answers:

1

Hi,

I have 2 domains .. master and details.

Master{
 String masterName; 
 static hasMany=[details:Detail]
}

Detail
{
  String detailName ; 
  static belongsTo =[master:Master];
}

I have form that handle the save

def save = {
 .....
 def master = new Master(params);
 params.detailsName.eachWithIndex(dtName, index ->
   def detail = new Detail();
   detail.detailName = dtName; 
   ....
   master.addToDetails(detail);
 }
  .....
 master.save(flush:true);
}

when I called master.save(), if there are errors in detail, the master still saving the data. I want to know how to cancel master if there are errors in details and i would like to know how to track the errors in details ?

thanks

+2  A: 

A transaction is what you need. You could perform the save in a service. In services with transaction=true, all methods are wrapped in transactions and there will be an automated rollback if any exception is thrown:

class MasterService {

    boolean transactional = true

    def save(...) { }
}

Or you could use the withTransaction closure in your controller to wrap your code in a transaction if you don't want to create a service.

John Wagenleitner
i did using transaction, but i have no idea how to know that there is error/detail is not valid to be inserted (may be the name is blank or date is null etc).as far as i know, when detail was not valid, the header still inserted and it caused detail couldn't be saved. once you addTo*() it will attach the object without raising any errors. but when you save() the detail wont saved if there are errors and i cannot get the error message.
nightingale2k1
You can check detail.validate() and if false you can check the errors using detail.errors.each { log.debug it }.
John Wagenleitner