Monday, October 28, 2019

TRIGGER.NEWMAP AND TRIGGER.OLDMAP IN APEX TRIGGER


So now we have understood that trigger.newMap returns a new map of records with id and trigger.oldMap  returns an old map of records with id. Let us try to understand the same again by taking an example.

SCENARIO: We are going to update the Account record phone number from a particular value to a new value and we will be using trigger.newMap and trigger.oldMap to see the old and the new value before and after the update is done to a record.

APEX TRIGGER:

trigger AccountMainTrigger on Account (before update) {
    createContactClass obj=new createContactClass();
    if(trigger.isbefore && trigger.isupdate)
    {
     obj.method1(trigger.new,trigger.old,trigger.newMap,trigger.oldMap);
    }
}

APEX CLASS:

public class createContactClass {
    public void method1(List<Account> newList,List<Account> oldList,Map<id,Account> newMap,Map<id,Account> oldMap){
        for(Account obj:newList){
            system.debug('New Value of phone from newMap'+newMap.get(obj.id).phone);
        }
        for(Account obj1:oldList){
            system.debug('Old Value of phone from oldMap'+oldMap.get(obj1.id).phone);
        }

    }
}

Account record in the initial stage,

difference between trigger newmap and trigger oldmap in salesforce

Now let us update the phone number on the Account record,

difference between old map and new map

Now go to “Developer console” as shown in the below image to check the debug values,


trigger.oldmap and trigger.newmap in salesforce example

2 comments: