Comparing Old and New value of the record in Apex Trigger

by Rijwan Mohmmed
0 comment

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: {
        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
            System.debug('Opportunity StageName has not been updated');

Reference :

  1. Apex Trigger

You may also like

Leave a Comment