0

trying to figure out why new map provided by salesforce if old map already exist. every one providing difference is there but i am unable to find exact answer,

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.

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.

suggest please.

2 Answers 2

1

In trigger.Oldmap you get the old values while in trigger.newmap you get the new updated values.

Both of there return type is Map. With the help of list we can compare them.

Normally we use trigger.New and Trigger.oldMap to compare old and new value without need of nested loops.

for(Account acc: trigger.new)
  if(acc.active__c && trigger.oldmap.get(acc.Id).active__c  != acc.active__c)
      //comparing active status and also checking status is changed in update of this record
1

Here is an usecase that i have come across. I need to update Qualified__c checkbox on lead if Status changed to "Qualified". I need to update only when lead status is not "Qualified" before updating. In such situation we can take advantage of Trigger.newMap, Trigger.oldMap, Trigger.new, Trigger.old

trigger LeadTrigger on Lead (before update) {   
    for (Lead l : Trigger.new) {
        // Get the "old" using its ID in Trigger.oldMap
        Lead oldLead = Trigger.oldMap.get(l.Id);

        // Check that Status field not equal "Qalified" before and now changed to "Qualified" then only do update else display error
        if (!oldLead.Status.equals('Qualified') && l.Status.equals('Qualified')) {
           l.Qualified__c = true;
        }
        else{
           l.adderror('Lead status is not changed.');
        }
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .