What are Apex Triggers?

What are Apex Triggers in Salesforce? | The Developer Guide

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 events:

  • 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
}

dont miss out iconDon't forget to check out: Why Salesforce Apex Trigger is Unique?

What are the Trigger Context Variables?

  1. isExecuting
  2. isInsert
  3. isUpdate
  4. isDelete
  5. isBefore
  6. isUndelete
  7. isAfter
  8. newMap
  9. oldMap
  10. 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:
    • Updates the record again.
    • Runs system validations again. Custom validation rules, flows, duplicate rules, processes, and escalation rules aren’t run again.
    • Executes before update triggers and after update triggers, regardless of the record operation (insert or update), one more time (and only one more time)
    • Executes escalation rules.
    • Executes these Salesforce Flow automations, but not in a guaranteed order.
  12. When a process or flow executes a DML operation, the affected record goes through the same procedure.
  13. Executes record-triggered flows that are configured to run after the record is saved.
  14. Executes entitlement rules.
  15. If the record contains a roll-up summary field or is part of a cross-object workflow, perform calculations and update the roll-up summary field in the parent record. Parent record goes through the save procedure.
  16. 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.
  17. Executes Criteria Based Sharing evaluation.
  18. Commits all DML operations to the database.
  19. After the changes are committed to the database, executes post-commit logic is 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

dont miss out iconCheck out another amazing blog by Aman here: How to call Apex Method from Flow and Vice – Versa? | Salesforce Apex

Consider the following points Before creating triggers:

  • Upsert triggers to 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

Responses

Popular Salesforce Blogs