Tuesday, October 31, 2017

Trigger events & Context Variables

Trigger Context Variables
All triggers define implicit variables that allow developers to access run-time context. These variables are contained in the System.Trigger class.
VariableUsage
isExecutingReturns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
isInsertReturns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.
isUpdateReturns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.
isDeleteReturns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.
isBeforeReturns true if this trigger was fired before any record was saved.
isAfterReturns true if this trigger was fired after all records were saved.
isUndeleteReturns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)
newReturns a list of the new versions of the sObject records.
This sObject list is only available in insertupdate, and undelete triggers, and the records can only be modified in before triggers.
newMapA map of IDs to the new versions of the sObject records.
This map is only available in before updateafter insertafter update, and after undelete triggers.
oldReturns a list of the old versions of the sObject records.
This sObject list is only available in update and delete triggers.
oldMapA map of IDs to the old versions of the sObject records.
This map is only available in update and delete triggers.
sizeThe total number of records in a trigger invocation, both old and new.
Note
If any record that fires a trigger includes an invalid field value (for example, a formula that divides by zero), that value is set to null in the newnewMapold, and oldMap trigger context variables.
For example, in this simple trigger, Trigger.new is a list of sObjects and can be iterated over in a for loop, or used as a bind variable in the IN clause of a SOQL query.
01Trigger simpleTrigger on Account (after insert) {
02    for (Account a : Trigger.new) {
03        // Iterate over each sObject
04    }
05 
06    // This single query finds every contact that is associated with any of the
07    // triggering accounts. Note that although Trigger.new is a collection of 
08    // records, when used as a bind variable in a SOQL query, Apex automatically
09    // transforms the list of records into a list of corresponding Ids.
10    Contact[] cons = [SELECT LastName FROM Contact
11                      WHERE AccountId IN :Trigger.new];
12}
This trigger uses Boolean context variables like Trigger.isBefore and Trigger.isDelete to define code that only executes for specific trigger conditions:
01trigger myAccountTrigger on Account(before delete, before insert, before update,
02                                    after delete, after insert, after update) {
03if (Trigger.isBefore) {
04    if (Trigger.isDelete) {
05 
06        // In a before delete trigger, the trigger accesses the records that will be
07        // deleted with the Trigger.old list.
08        for (Account a : Trigger.old) {
09            if (a.name != 'okToDelete') {
10                a.addError('You can\'t delete this record!');
11            }
12        }
13    else {
14 
15    // In before insert or before update triggers, the trigger accesses the new records
16    // with the Trigger.new list.
17        for (Account a : Trigger.new) {
18            if (a.name == 'bad') {
19                a.name.addError('Bad name');
20            }
21    }
22    if (Trigger.isInsert) {
23        for (Account a : Trigger.new) {
24            System.assertEquals('xxx', a.accountNumber);
25            System.assertEquals('industry', a.industry);
26            System.assertEquals(100, a.numberofemployees);
27            System.assertEquals(100.0, a.annualrevenue);
28            a.accountNumber = 'yyy';
29        }
30 
31// If the trigger is not a before trigger, it must be an after trigger.
32else {
33    if (Trigger.isInsert) {
34        List<Contact> contacts = new List<Contact>();
35        for (Account a : Trigger.new) {       
36            if(a.Name == 'makeContact') {
37                contacts.add(new Contact (LastName = a.Name,
38                                          AccountId = a.Id));
39            }
40        }
41      insert contacts;
42    }
43  }
44}}}

Context Variable Considerations

Be aware of the following considerations for trigger context variables:
  • trigger.new and trigger.old cannot be used in Apex DML operations.
  • You can use an object to change its own field values using trigger.new, but only in before triggers. In all after triggers, trigger.new is not saved, so a runtime exception is thrown.
  • trigger.old is always read-only.
  • You cannot delete trigger.new.
The following table lists considerations about certain actions in different trigger events:
Trigger EventCan change fields using trigger.newCan update original object using an update DML operationCan delete original object using a delete DML operation
before insertAllowed.Not applicable. The original object has not been created; nothing can reference it, so nothing can update it.Not applicable. The original object has not been created; nothing can reference it, so nothing can update it.
after insertNot allowed. A runtime error is thrown, as trigger.new is already saved.Allowed.Allowed, but unnecessary. The object is deleted immediately after being inserted.
before updateAllowed.Not allowed. A runtime error is thrown.Not allowed. A runtime error is thrown.
after updateNot allowed. A runtime error is thrown, as trigger.new is already saved.Allowed. Even though bad code could cause an infinite recursion doing this incorrectly, the error would be found by the governor limits.Allowed. The updates are saved before the object is deleted, so if the object is undeleted, the updates become visible.
before deleteNot allowed. A runtime error is thrown. trigger.new is not available in before delete triggers.Allowed. The updates are saved before the object is deleted, so if the object is undeleted, the updates become visible.Not allowed. A runtime error is thrown. The deletion is already in progress.
after deleteNot allowed. A runtime error is thrown. trigger.new is not available in after delete triggers.Not applicable. The object has already been deleted.Not applicable. The object has already been deleted.
after undeleteNot allowed. A runtime error is thrown.Allowed.Allowed, but unnecessary. The object is deleted immediately after being inserted.

No comments:

Post a Comment

Lightning Inter-Component Communication Patterns

Lightning Inter-Component Communication Patterns If you’re comfortable with how a Lightning Component works and want to build producti...