function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
CvrKCvrK 

Perfect use cases to use trigger.newmap and trigger.oldmaps instead of trigger.new and trigger.old

Hi 
can some one describe me some perfect use cases where trigger.newmap works instead of trigger.new and similarly where only trigger.oldmap works better than trigger.old
 
Himanshu ParasharHimanshu Parashar
Hi,

According to the docs, Trigger.new returns a list, which are ordered, and Trigger.newMap returns a map - which are unordered.  

What to use depends on what you're doing - if you have an ID of an object you need to do something with, using the map makes more sense as you can use newMap.get(). Otherwise you'd have to loop over all the elements in Trigger.new and look for a matching ID. Similarly, if you have multiple loops over each item the trigger is operating on, the list returned by Trigger.new may be the better bet.


Here is one example.
 
for(Opportunity opp : Trigger.new){
                    //Create an old and new map so that we can compare values
                    Opportunity oldOpp = Trigger.oldMap.get(opp.ID);    
                    Opportunity newOpp = Trigger.newMap.get(opp.ID);
                    
                    //Retrieve the old and new Reseller Email Field            
                    string oldResellerEmail = oldOpp.Reseller_Email__c;
                    string newResellerEmail = newOpp.Reseller_Email__c;
                   
                    //If the fields are different, the email has changed
                    if(oldResellerEmail != newResellerEmail){
                        oppIDs.put(opp.Id,opp.Reseller_Email__c);    
                    }
}

Thanks,
Himanshu