How To Compare Old Values And New Values In Salesforce Triggers (How to check whether record values are changed or not in Apex Trigger)
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<account> newList, Map<Id,Account> 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);
}
}
No Comment to " How To Compare Old Values And New Values In Salesforce Triggers "