Apex Triggers in Salesforce

Aman Garg
4 min readMar 25, 2023

--

What are Triggers?

Apex can be invoked by using triggers. Apex triggers enable you to perform custom actions before or after changes to Salesforce records, such as insertions, updates, or deletions.

What are the Different types of Triggers in Salesforce?

There are two types of triggers:

  • Before triggers are used to update or validate record values before they’re saved to the database.
  • After triggers are used to access field values that are set by the system (such as a record’s Id field), and to affect changes in other records, such as logging into an audit table or firing asynchronous events with a queue. The records that fire the after trigger are read-only.

Types of Trigger event:

  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete

Trigger Syntax

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

What are the Trigger Context Variables?

  1. isExecuting
  2. isInsert
  3. isUpdate
  4. isDelete
  5. isBefore
  6. isUndelete
  7. isAfter
  8. new
  9. newMap
  10. old
  11. oldMap
  12. size
  13. opeartionType

Order of Execution in Triggers

  1. Loads the original record from the database or initializes the record for an upsert statement.
  2. Loads the new record field values from the request and overwrites the old values.
  3. Executes record-triggered flows that are configured to run before the record is saved.
  4. Executes all before triggers.
  5. Runs most system validation steps again, such as verifying that all required fields have a non-null value, and runs any custom validation rules. The only system validation that Salesforce doesn’t run a second time (when the request comes from a standard UI edit page) is the enforcement of layout-specific rules.
  6. Executes duplicate rules. If the duplicate rule identifies the record as a duplicate and uses the block action, the record isn’t saved and no further steps, such as after triggers and workflow rules, are taken.
  7. Saves the record to the database, but doesn’t commit yet.
  8. Executes all after triggers.
  9. Executes assignment rules.
  10. Executes auto-response rules.
  11. Executes workflow rules. If there are workflow field updates:
  12. Updates the record again.
  13. Runs system validations again. Custom validation rules, flows, duplicate rules, processes, and escalation rules aren’t run again.
  14. Executes before update triggers and after update triggers, regardless of the record operation (insert or update), one more time (and only one more time)
  15. Executes escalation rules.
  16. Executes these Salesforce Flow automations, but not in a guaranteed order.
  17. When a process or flow executes a DML operation, the affected record goes through the save procedure.
  18. Executes record-triggered flows that are configured to run after the record is saved.
  19. Executes entitlement rules.
  20. If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.
  21. If the parent record is updated, and a grandparent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the grandparent record. Grandparent record goes through save procedure.
  22. Executes Criteria Based Sharing evaluation.
  23. Commits all DML operations to the database.
  24. After the changes are committed to the database, executes post-commit logic are executed. Examples of post-commit logic (in no particular order) include:
  • Sending email
  • Enqueued asynchronous Apex jobs, including queueable jobs and future methods
  • Asynchronous paths in record-triggered flows

consider these following points Before creating triggers:

  • upsert triggers fire both before and after insert or before and after update triggers as appropriate.
  • Triggers that execute after a record has been undeleted only work with specific objects.
  • merge triggers fire both before and after delete for the losing records, and both before and after update triggers for the winning record.
  • Callouts must be made asynchronously from a trigger so that the trigger process isn’t blocked while waiting for the external service’s response. The asynchronous callout is made in a background process, and the response is received when the external service returns it. To make an asynchronous callout, use asynchronous Apex such as a future method.

Fields Not Updateable in Before Triggers or After Trigger

  • Fields Not Updateable in Before 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 Not Updateable in After Triggers

Trigger Best Practices

  1. One Trigger Per Object
  2. Logic-less Triggers
  3. Context-Specific Handler Methods
  4. Bulkify your Code
  5. Avoid SOQL Queries or DML statements inside FOR Loops
  6. Using Collections, Streamlining Queries, and Efficient For Loops
  7. Querying Large Data Sets
  8. Use @future Appropriately
  9. Avoid Hardcoding IDs
  10. Execute DML statements using collections instead of individual records per DML statement.
  11. Use Collections in SOQL “WHERE” clauses to retrieve all records back in single query
  12. Use a consistent naming convention including the object name

Originally published at http://amansfdc.wordpress.com on March 25, 2023.

--

--

Aman Garg

Sr. Executive - Training || 5x Salesforce Certified || 2x Copado Certified || Salesforce Mentor || Founder of Salesforce Learners