Comparing Old And New Values In A Trigger

by | Aug 2, 2022 | Salesforce

Home » Salesforce » Comparing Old And New Values In A Trigger

Introduction

Salesforce has given us some automation tools like workflows, process builders, and flows through which we can do automation by doing configuration.

In the same way, we have triggers which is a programming approach to perform different automation actions.

What is a trigger in Salesforce?

A trigger is an Apex code used to automate actions depending on the events that are getting fired.

Note: Trigger is object-specific. We cannot write triggers on two objects in a single code.

DML events – before insert, after insert,

before update, after update,

before delete, after delete,

after undelete

We have multiple context variables in the trigger, which are used to capture the value of the current context in our apex code

Like, Trigger.new – it holds the list of sobject records that are inserted, updated, or undeleted.

Trigger.old – it holds the list of sobject records which are getting updated or deleted

and many more…..

How to compare Trigger.new values with Trigger.old values?

Sometimes, we get a requirement in which we want our trigger to execute when the field value is changed on a record to ensure that our trigger doesn’t run whenever the record is updated. For this, we need to compare whether the old value is equal to the new value. If the old value of that field is not equal to the new value, it means the field value has changed, and then only the trigger should fire.

Salesforce has given us Trigger.oldMap where the old version of the record gets stored on the map with the key as Id.

Example

Requirement: Write a trigger to update the Description field of Lead if the rating is changed.

trigger LeadRating on Lead (before update) {

for(Lead l : Trigger.new){

if(Trigger.oldMap.get(l.Id).Rating != l.Rating){

l.Description = 'Rating has changed from ' + Trigger.oldMap.get(l.Id).Rating + ' to ' + l.Rating;

}

}

}

 

Explanation: In the above trigger, we are checking if the rating value has changed or not. If it has changed, then update the description field accordingly with the old and new values of the field.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author