top of page

When to use Trigger.oldMap & Trigger.newMap?

use case:

If the opportunity has been changed to 'Closed Won' then check the checkbox.


Solution:

Trigger.new returns a list, which are ordered, and Trigger.newMap returns a map - which are unordered.

Trigger.newMap is available for before update, after update, after insert and after undelete.

Trigger.oldMap is available for update and delete.


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.

trigger Winning on Opportunity (before update) { for (Opportunity opp : Trigger.new) { // Access the "old" record by its ID in Trigger.oldMap Opportunity oldOpp = Trigger.oldMap.get(opp.Id);

Opportunity newOpp = Trigger.newMap.get(opp.Id); // Trigger.new records are conveniently the "new" versions! Boolean oldOppIsWon = oldOpp.StageName.equals('Closed Won'); Boolean newOppIsWon = newOpp.StageName.equals('Closed Won'); // Check that the field was changed to the correct value if (!oldOppIsWon && newOppIsWon) { opp.I_am_Awesome__c = true; } } }

Recent Posts

See All

Comments


Post: Blog2_Post

©2020 by SalesforceDemystified. Proudly created with Wix.com

bottom of page