9

Trigger.oldMap in Salesforce| Context Variables in Apex Triggers

Trigger.oldMap in Salesforce returns a map of record IDs to the old version of sObject records, and is available in update and delete triggers.

Trigger.oldMap Example:

Apex Trigger oldMap Example:

trigger OpportunityTrigger on Opportunity (before update) {
    Map<Id, Opportunity> oMap = Trigger.oldMap;

        for (Opportunity newOpp: Trigger.new) {
        Opportunity oldOpp = oMap.get(newOpp.Id);
        if (newOpp.Amount != oldOpp.Amount) {
            newOpp.addError(‘Amount cannot be changed’);
        }
    }
}

In this example, Trigger.oldMap helps compare old and new Opportunity records, ensuring that certain fields, like Amount, are not altered during the update.

Next Topic

Need more support?

Get a head start with our FREE study notes!

Learn more and get all the answers you need at zero cost. Improve your skills using our detailed notes prepared by industry experts to help you excel.

Frequently Asked Questions

What is Trigger.oldMap in Salesforce?

Trigger oldmap in Salesforce is an Apex trigger variable that returns a Map of record IDs mapped to old versions.

What is the difference between Trigger.old and Trigger.oldMap?

Trigger.old is a list of old sObjects, while Trigger.oldMap is a map of record IDs to old sObject records.

Can we modify Trigger.oldMap records?

No, the Trigger.oldMap records are only read. They cannot be modified, and doing so can cause errors.

What happens if we use Trigger.oldMap in the insert trigger?

Trigger.oldMap is not available in insert triggers because new records have no prior versions.

Book Free15-Minutes Career Counselling