+ Start a Discussion

When we use trigger.olmap and trigger.newmap?pls give some examples...urgent help needed

Hi All,


I am confusing on Oldmap and newmap while writing triggers Pls provide and explain some example code then it will be very helpful to mee...








Trigger.newMap - A map of IDs to the new versions of the sObject records.Note that this map is only available in before update, after insert, and after update triggers.


Trigger.oldMap - A map of IDs to the old versions of the sObject records.Note that this map is only available in update and delete triggers.


Note :   Trigger.newMap dont work for before insert while Trigger.New works fine for holding all Ids of records while inserting.

According to the docs, Trigger.new returns a list, which are ordered, and Trigger.newMap returns a map - which are unordered. The docs specifically state you should not rely on the ordering of a map's elements.


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.


for more detail follow the below link -




For example 

Let say you have a requirement where you want to save the previoues owner of an account when the account owner is changed. You understand that you need to create a  trigger on update for account. Let say you click edit button and the owner is abc. Now you need to check that if owner is changed whehter it is defferent from previuos one.Here comes the need of trigger.oldmap. You check that if the  new entered owner let say xyz is same of diffrent from the previous owner. You can do that trigger.oldmap.account.owner(abc)== trigger.newmap.account.owner (xyz)..(just an example as this is not the right way to access account owner field).


Thanks for reply ..


Can you please  put the code..then it will be easily understandable....









Triggers aren't granular like that. In the before update trigger, use the Trigger.New andTrigger.OldMap variables to compare each new record to see if the fields you're interested in have changed.


go through this link


for (Opportunity newOpp : Trigger.new) {
    Opportunity oldOpp = Trigger.oldMap.get(newOpp.Id);
    if (oldOpp.Name != newOpp.Name) {
        // do something
Yoganand GadekarYoganand Gadekar



See if this example expalins your Query:



Hit kudos and mark as answer if it helps you.