2

I am new to salesforce and apex and when reading about triggers, I found this confusing.

Could somebody clarify on this please?

From salesforce documentation:

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.

If Trigger.newMap givesAccess to the new version of SObjects why we need to use this in before events?

If i use Trigger.newMap in beforeUpdate will I get old values of the record of new values of the record?

Is my understanding correct? For the events before Update, after Update we have access to the variables Trigger.old and Trigger.new

1

New map, as the name suggests, is to provide access to the new values the records will take on during the DML operation.

You might want this in before events to perform some kind of validation, for example (pseudeocode):

for each record in trigger.old
  if record.field == 'A' && trigger.newMap.get(record.Id).field == 'C'
    error('You can not change field straight from A to C!');

Using newMap in a Before Update trigger will let you access the new field values, oldMap will provide you with the existing values. As you can see from the above, it's useful to have access to both so that you can take action as business logic dictates.

| improve this answer | |
  • I knwo that to update record in before trigger you just change record in trigger.new but is change in trigger.newMap also work and change records? – Marcin Trofiniak Dec 11 '19 at 11:26
  • 1
    @MarcinTrofiniak Yep, the map is just a map of ID -> Object Reference. The list and the map refer to the same objects in memory, so changes you make either way will be working on the same records. – Matt Lacey Dec 12 '19 at 3:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.