Compare field changes in apex trigger
Triggers often need to check for field value changes in order to execute the business logic. A real-world example would be checking if the payment status has been updated to 'Paid' to process an order.
To write an efficient trigger, always check if a field's value has been updated before running your code. Triggers can run multiple times when a record is saved. To avoid processing the same record more than once, compare the old value and the new value, and only run your code if the value has changed.
Since context variables variables provide the old and new versions of the records in a transaction, it becomes easy to detect field changes in the trigger handler.
Lets assume if you want to detect if the account industry is updated, here is how you can perform that in apex.
In the above example:
The line number
6
gets all account records from the trigger context variabletrigger.new
The for loop for collection is used on line number
8
to go through all account records.To detect industry field value change on account, the previous version of account record is retrieved from the
trigger.OldMap
on line number10
and compared its values with new account on line number12
.
Note
Always use as many filters as possible when running a specific trigger logic as triggers runs for all database record and limit your code execution only when necessary. This helps to reduce the governor limits usage in salesforce.