<aside>
💡
Key Points from Trailhead: Apex Triggers
</aside>
1. Purpose:
- Perform custom actions before or after events (DML Operations) on Salesforce objects.
- Can't be used for tasks achievable through point-and-click tools (use validation rules, flows).
- Useful for complex logic, performance-critical tasks, or CPU-intensive operations.
2. Types of Triggers:
- Before triggers: Update/validate record values before saving.
- After triggers: Access system-set field values (Id, LastModifiedDate) and modify other records.
3. Using Context Variables:
- Access records triggering the event:
Trigger.new: New versions of inserted/updated records (read-only in before triggers).
Trigger.old: Old versions of updated records (in update triggers) or deleted records (in delete triggers).
Trigger.isBefore, Trigger.isAfter: Flags indicating trigger execution timing.
- Other context variables provide details about the trigger context (e.g.,
Trigger.isInsert, Trigger.size).
4. Using Trigger Exceptions with addError():
- Marks a trigger record with a custom error message and prevents any DML operation.
5. Triggers and Callouts:
- Triggers can make asynchronous calls to external Web services.
- Use future methods with
@future(callout=true) annotation for asynchronous execution.
<aside>
💡
Important Interview Questions for Apex Triggers
</aside>
1. When would you use an Apex Trigger?
- Answer: When I need to perform custom actions based on data changes in Salesforce, such as:
- Sending notifications (e.g., email on opportunity creation)
- Updating related records (e.g., update account industry when contact industry changes)
- Enforcing business rules (e.g., prevent deletion of accounts with related contacts)
flowchart LR
subgraph Apex Trigger
A(When to use an Apex Trigger)
B(Sending notifications)
C(Updating related records)
D(Enforcing business rules)
end
A --> B
A --> C
A --> D
2. What is the purpose of the Trigger.isExecuting property?