Free computer code on screen

Comparing Old And New Field Values In A Salesforce Trigger

Occasionally, there’s a requirement for a trigger to execute only when specific field values on a record change. To ensure the trigger operates solely when necessary, it’s crucial to compare the value of that field between the old and new versions of the record. For instance, there might be a need to send an email to the VP of a company or perform a task when an opportunity’s status transitions to “Closed Won.” Thus, comparing the old and new field values within the trigger becomes essential for accurate execution.

Salesforce provides Trigger.OldMap, where records with their older versions (the last committed version in the database) are stored in a map using their Salesforce record IDs as keys.

Trigger.OldMap = Map<Id, OldVersionOfRecord>();

Below is an example demonstrating how we can utilize Trigger.OldMap and Trigger.New context variables to compare field values. The record ID is common in both Trigger.OldMap and Trigger.New, allowing us to retrieve the older and newer versions of any record from these maps.

In this example, the trigger compares the ‘Account Number’ field’s old value with the new value. Essentially, the trigger checks for changes in the account number field. If the account number is altered, the trigger sets the ‘Type’ field value to “prospect”; otherwise, it assigns it a value of “Other”.

trigger Compare_OldandNewvalues on Account (before update) {
 
//Here we will iterate on trigger.new list, which already holds the new values of all records.
for (Account acc: Trigger.new) {
//Here we use the account id, to get the older version of record.
Account oldAccount = Trigger.oldMap.get(acc.ID);
 
//once we get the older version, we can get any field's value from older version to compare.
if(acc.AccountNumber != oldAccount.AccountNumber) {
 
//Here is some logic being performed on a condition basis.
System.debug('--*Account Number is changed*--');
System.debug('**Old Account Number :'+oldAccount.AccountNumber);
System.debug('**New Account Number :'+acc.AccountNumber);
acc.Type = 'Prospect';
}
else{
System.debug('--**Account Number has not been Updated**--');
acc.Type = 'Other';
}
}
}

Additionally, it’s important to note that Trigger.oldMap is accessible only in update and delete events, and it’s not available in insert event triggers. Please consider this when composing your trigger code.