Free computer code on screen

What do Apex Triggers represent in Salesforce?| Insights from the Developer Guide

What do triggers entail

“Triggers in Apex can be activated to initiate custom actions either prior to or following modifications to Salesforce records, including inserts, updates, or deletions.”

What categories of triggers exist in Salesforce

There are two trigger categories

  • Before triggers, which are employed to modify or validate record values before they are saved in the database.
  • After triggers, which are used to access system-set field values (e.g., a record’s Id field) and to trigger changes in other records, such as logging them in an audit table or initiating asynchronous events with a queue. Records that activate after triggers are in read-only mode.

Trigger Event Categories

  • Prior to Insert
  • Prior to Update
  • Prior to Deletion
  • Following Insert
  • Following Update
  • Following Deletion
  • Following Restoration (Undelete)

Syntax for Triggers

trigger TriggerName on ObjectName (before insert, before update) {
// Write the code with the trigger event
}

“What do Trigger Context Variables encompass?”

  1. isExecuting
  2. isInsert
  3. isUpdate
  4. isDelete
  5. isBefore
  6. isUndelete
  7. isAfter
  8. newMap
  9. oldMap
  10. operationType

Sequence of Execution in Trigger Handlers

Here’s a rephrased version of the order of execution in triggers:

  1. Retrieves the original record from the database or initializes the record for an upsert statement.
  2. Populates the new record’s field values from the request and replaces the old values.
  3. Executes record-triggered flows configured to run before saving the record.
  4. Processes all before triggers.
  5. Reevaluates most system validation steps, such as ensuring all required fields have non-null values, and applies any custom validation rules. Salesforce does not repeat certain system validations, like enforcing layout-specific rules, when the request originates from a standard UI edit page.
  6. Enforces duplicate rules. If a duplicate rule identifies the record as a duplicate and uses the block action, the record isn’t saved, and subsequent actions like after triggers and workflow rules are skipped.
  7. Persists the record to the database but doesn’t finalize the transaction.
  8. Executes all after triggers.
  9. Enacts assignment rules.
  10. Applies auto-response rules.
  11. Executes workflow rules. If workflow field updates are triggered:
  • Updates the record once more.
  • Reapplies system validations. Custom validation rules, flows, duplicate rules, processes, and escalation rules are not rechecked.
  1. Reexecutes before update triggers and after update triggers, regardless of the record operation (insert or update), one additional time (and only one more time).
  2. Executes escalation rules.
  3. Handles Salesforce Flow automations, but without a guaranteed order.
  4. When a process or flow performs a DML operation, the affected record follows the same procedure.
  5. Runs record-triggered flows configured to run after saving the record.
  6. Applies entitlement rules.
  7. If the record contains a roll-up summary field or is part of a cross-object workflow, computes and updates the roll-up summary field in the parent record. The parent record undergoes the save procedure.
  8. If the parent record is updated and a grandparent record contains a roll-up summary field or is part of a cross-object workflow, computes and updates the roll-up summary field in the grandparent record. The grandparent record undergoes the save procedure.
  9. Evaluates Criteria-Based Sharing.
  10. Commits all DML operations to the database.
  11. After the changes are committed to the database, executes post-commit logic, which may include actions like:
  • Sending emails
  • Enqueuing asynchronous Apex jobs, including queueable jobs and future methods
  • Handling asynchronous paths in record-triggered flows

Take into account the following considerations prior to creating triggers

“Ensure the following considerations are accounted for when working with triggers:

  1. For upsert triggers, they should activate for both before and after insert or before and after update events, as appropriate.
  2. Keep in mind that triggers designed to execute after a record has been undeleted are only compatible with specific objects.
  3. Merge triggers will trigger both before and after delete events for the losing records, and both before and after update events for the winning record.
  4. To prevent blocking the trigger process while waiting for an external service’s response, callouts must be made asynchronously. Asynchronous callouts are initiated in the background, and the response is received when the external service provides it. For such asynchronous callouts, employ asynchronous Apex mechanisms like a future method.”

Fields Inaccessible for Updates in Before and After Triggers

  • Task.isClosed
  • Opportunity.amount*
  • Opportunity.ForecastCategory
  • Opportunity.isWon
  • Opportunity.isClosed
  • Contract.activatedDate
  • Contract.activatedById
  • Case.isClosed
  • Solution.isReviewed
  • Id (for all records)**
  • createdDate (for all records)**
  • lastUpdated (for all records)
  • Event.WhoId (when Shared Activities is enabled)
  • Task.WhoId (when Shared Activities is enabled)

Fields Inaccessible for Updates in After Triggers:”

Best Practices for Triggers

  1. Limit One Trigger per Object
  2. Create Logic-Light Triggers
  3. Implement Context-Specific Handler Methods
  4. Ensure Bulk Processing
  5. Refrain from Including SOQL Queries or DML Statements within FOR Loops
  6. Leverage Collections, Optimize Queries, and Employ Efficient For Loops
  7. Exercise Caution When Querying Large Data Sets
  8. Use @future Appropriately for Asynchronous Processing
  9. Avoid Hardcoding IDs
  10. Perform DML Operations Using Collections Rather Than Individual Records
  11. Employ Collections in SOQL ‘WHERE’ Clauses for Efficient Record Retrieval
  12. Maintain a Consistent Naming Convention, Including the Object Name”