Now that we understand that trigger.newMap returns a map of new records with their IDs, and trigger.oldMap returns a map of old records with their IDs, let's explore this concept further with an example.
Scenario:
We will update the phone number of an Account record, changing it from a specific value to a new one. By using trigger.newMap and trigger.oldMap, we can observe both the old and new values of the phone number before and after the update is made to the record. This example will help us better understand how these trigger maps reflect changes during the update operation.
APEX TRIGGER:
Description:
The APEX Trigger AccountMainTrigger is fired before an update on the Account object. Within the trigger, it creates an instance of the createContactClass and calls the method1 to compare the old and new phone numbers of the Account records being updated.
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:
The createContactClass class contains a method, method1, that takes four parameters: two lists of Account records (newList and oldList) and two maps (newMap and oldMap) of Account records keyed by their IDs.
The method loops through newList to fetch and debug the new phone number of each Account using newMap. It also loops through oldList to fetch and debug the old phone number using oldMap.
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);
}
}
}
The image below shows the Account record in its initial stage, before any updates or changes have been made. It displays the original values of the Account fields as they exist at the start.
Now let us update the phone number on the Account record,
Now go to “Developer console” as shown in the below image to
check the debug values,
Thank you.. It was helpful
ReplyDeleteGreat thanks
ReplyDelete