How To Compare Old Values And New Values In Salesforce Triggers

How To Compare Old Values And New Values In Salesforce Triggers (How to check whether record values are changed or not in Apex Trigger)

We know that salesforce Before update and After Update triggers fired/invoked based on Update DML event occurs, irrespective of any field value updated on record. But update triggers should not get invoked every time when record is updated. These trigger's should fire when corresponding field values got changed on record.

If we want to know whether respective field value changed or not, we need to use trigger.new and trigger.oldMap context variables. As we know that trigger.New contains list of records which will have updated field values and trigger.OldMap contains map of records which will have old values. Lets take basic example: If Phone field value on Account got changed, then update Description field like "Phone number got updated from old Phone Number to New Number. Here the logic should not trigger every time, only gets triggered when only phone field value got updated.

Trigger Helper Class

public class Account_Helper {
  public static void checkPhoneValueUpdated(List newList, Map  oldMap) {
     for(Account accountRecord: newList){
      if(accountRecord.phone != oldMap.get(accountRecord.Id).phone){
          accountRecord.description = 'Phone number got updated from'+oldMap.get(accountRecord.Id).phone+' to '+accountRecord.phone;
       }
     }
  }
}

Trigger:

Trigger AccountTrigger on Account(Before  update){
    if(trigger.isBefore && trigger.isUpdate){
        Account_Helper.checkPhoneValueUpdated(trigger.new, trigger.oldMap);
    }
}

Post a Comment