How to determine which field has been updated in afterUpdate | beforeUpdate GORM Methods
I am using the afterUpdate method reflected by the GORM API in a grails project.
class Transaction{
Person receiver;
Person sender;
}
I want to know which field was changed to execute afterUpdate
:
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 with the object before updating in a global variable (previously as a transaction), then in afterUpdate compare previous
with the current object. May be?
source to share
This is usually done 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 use afterUpdate()
, the value is already stored in the database and isDirty
will never return true.
You will need to do your own checks with beforeUpdate
. This may mean a transitional meaning 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)
...
}
...
}
source to share