How To Compare Old Values And New Values in Salesforce Triggers. (How to check whether record values are changed or not in Apex Triggers).
We understand that salesforce Before update and After Update triggers fired/invoked based on Update DML event occurs. Regardless of any field value updated on record.
Trigger.OldMap contains an older version (last version of record committed in the database) of record in map with key as their Salesforce records Id’s.
Trigger.OldMap = Map<Id, OldVersionOfRecord>();
What is Apex Triggers in Salesforce ?
If we need to recognize whether or not the respective field value modified or not. We need to use trigger.new and trigger.oldMap context variables. As we know that trigger.New consists of a list of records so that it will have updated field values and trigger.OldMap consists of a map of records that will have old values.
Example: When email value will change on contact, then only update description field like. Check whether record values are changed or not in Apex Triggers.
trigger Helper Class
public class Contact_Helper {
public static void checkEmailValueUpdated(List<Contact> newList, Map<Id,Contact> oldMap) {
for(Contact conRecord: newList){
if(conRecord.phone != oldMap.get(conRecord.Id).phone){
conRecord.description = 'Email got updated from'+oldMap.get(conRecord.Id).email+' to '+conRecord.email;
}
}
}
}
Trigger:
Trigger ContactTrigger on Contact(Before update){
if(trigger.isBefore && trigger.isUpdate){
Contact_Helper.checkEmailValueUpdated(trigger.new, trigger.oldMap);
}
}
Notes:
- Trigger.oldMap is only available in update and delete events.
- Trigger.oldMap is not available in insert event triggers. Please take care of this factor while writing your apex trigger code.
For more details refer to the official Apex Triggers link.