This course is currently a work in progress. Please join the waitlist to receive regular updates.

Accessing records in an Apex trigger

Accessing record values are important to make changes on the same record or related records in context of an apex trigger.

Trigger context variables provided by apex can be used to access the record values.

Access records

To access the current records being triggered, use the trigger.new context variable. This variable always returns a list of SObjects. Use typecast operation to convert it as a specific object type (e.g., Account, Contact).

List<Account> newAccounts = (List<Account>) Trigger.new;

To access the old version of the same records, use the trigger.old context variable

List<Account> newAccounts = (List<Account>) Trigger.Old;

Access records as map

To access the new records as a, map (key value pair), use the trigger.newMap context variable. This variable always returns a map with key as the recordId and value as the record.

Map<Id, Account> newAccountMap = (Map<Id, Account>) Trigger.newMap;

To access the old version of the records as a map, use the trigger.oldMap context variable

Map<Id, Account> oldAccountMap = (Map<Id, Account>) Trigger.oldMap;