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 :
- Only update event in trigger we have oldmap and newmap for compare values.
- check if any update in the particular field.
- Trigger.OldMap has the old version
- 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 :
What’s your Reaction?
+1
3
+1
+1
+1
+1
+1
3