Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect which field has been updated in afterUpdate|beforeUpdate GORM methods

i use afterUpdate method reflected by GORM API in grails project.

class Transaction{

    Person receiver;
    Person sender;


}

i want to know which field modified to make afterUpdate behaves accordingly :

class Transaction{
     //...............
   def afterUpdate(){
      if(/*Receiver is changed*/){
        new TransactionHistory(proKey:'receiver',propName:this.receiver).save();
      }
      else
      {
      new TransactionHistory(proKey:'sender',propName:this.sender).save();
      }

   }
}

I can use beforeUpdate: and catch up the object before updating in global variable (previous as Transaction), then in afterUpdate, compare previous with the current object. Could be?

like image 448
Abdennour TOUMI Avatar asked Sep 16 '14 13:09

Abdennour TOUMI


1 Answers

Typically this would be done by using the isDirty method on your domain instance. For example:

// returns true if the instance value of firstName 
// does not match the persisted value int he database.
person.isDirty('firstName')

However, in your case if you are using afterUpdate() the value has already been persisted to the database and isDirty won't ever return true.

You will have to implement your own checks using beforeUpdate. This could be setting a transient value that you later read. For example:

class Person {
  String firstName
  boolean firstNameChanged = false
  static transients = ['firstNameChanged']
  ..
  def beforeUpdate() {
    firstNameChanged = this.isDirty('firstName')
  }
  ..
  def afterUpdate() {
    if (firstNameChanged)
    ...
  }
...
}
like image 67
Joshua Moore Avatar answered Nov 15 '22 09:11

Joshua Moore