How To Determine If Record Values Have Been Modified In Apex Triggers

How to Compare Old and New Values in Salesforce Triggers In Salesforce triggers, we can check if record values have changed by comparing the old values to the new ones. The Before Update and After Update triggers are invoked based on the Update DML event occurring, regardless of which field value is updated on the record.

Trigger.OldMap contains the previous version (the last committed version of the record in the database) of the record in a map format, with the record IDs as keys. Trigger.OldMap = Map<Id, OldVersionOfRecord>();

What does the term Apex Triggers mean in Salesforce?

To determine if a specific field value has been modified, we utilize the context variables trigger.new and trigger.oldMap. In this context, trigger.new contains a list of records with updated field values, while trigger.oldMap contains a map of records with their old values.

For instance, let’s consider a scenario where we want to update the description field only when the email value on a contact changes. We can use Apex Triggers to check if record values have been modified in this manner.

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);  
  }  
}  
Remarks:

The Trigger.oldMap context variable is accessible only during update and delete events. It is not available in insert event triggers. When writing your Apex trigger code, please consider this aspect carefully.