Comparing Old and New value of the record in Apex Trigger

by Rijwan Mohmmed
0 comment
comparing-old-and-new-value-of-the-record-in-apex-trigger

Hello friends, today we will discuss Comparing Old and New values of the record in Apex Trigger. In Salesforce, trigger.oldmap is used to store all the old records in a map with keysets as their ids. The old field value of records can be compared with the new field value in the trigger. We compare the records by values in update event.

Also, check this: Relationship Query in Apex Salesforce

Key Highlights :

  1. Only update event in trigger we have oldmap and newmap for compare values.
  2. check if any update in the particular field.
  3. Trigger.OldMap has the old version
  4. Trigger.NewMap has new version.

Process & Code :

Here in the trigger, we will create task if opportunity stage change

trigger OpportunityTrigger on Opportunity (After update) {
     
    for (Opportunity opp: Trigger.new) {
        Opportunity oldOpportunity = Trigger.oldMap.get(opp.Id);
		
        if(opp.StageName != oldOpportunity.StageName) {
            System.debug('Opportunity StageName is changed');
            System.debug('Old Opportunity StageName ==>' + oldOpportunity.StageName);
            System.debug('New Opportunity StageName ==>' + opp.StageName);
            //create task
        }
        else{
            System.debug('Opportunity StageName has not been updated');
        }
    }
}

Reference :

  1. Apex Trigger
What’s your Reaction?
+1
3
+1
0
+1
0
+1
0
+1
0
+1
3

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.