Tuesday, December 20, 2022

Trigger basic concepts in Salesforce

concept of Trigger

Trigger is an apex code that gets executed whenever a specific DML operation is performed on an Object record. It allow developers to pro grammatically check for duplicate records, update fields across objects, automate the creation of new records based on criteria, and much more.
For example, if I wanted to check for duplicity on the user email field every time a user was created or updated I would write a trigger and assign the “before insert, before update” operations to it. This would allow me to query the database and throw an exception if a duplicate is found before saving to the database.
Triggers can be primarily classified into two types:
  • Before trigger
  • After trigger
Before Triggers:  Before triggers are ones that get executed before the record is saved to the database.
After Triggers: After triggers are ones that get executed after the record is saved to the database.
Each one has its own significance as each one has to be used in specific scenarios.
Usage of Before Triggers:
  • Can be used to perform validations and stop the creation / updation / deletion of records if they are not satisfying the criteria.
  • Data can be modified in before triggers only, hence record field auto population by the system can be performed here.
Usage of After Triggers:
  • By the time these triggers execute the record ID and the system generated fields such as created by, modified by etc… are generated by the system and these fields such as ID can be used to build relationships i.e create relationship records.
Trigger Syntax:
trigger <triggerName> on <Object>( DML Events ) {
/* — Execute Trigger Logic Here — */
}
DML Events: Below are the DML events that can be specified on a trigger.
  • Before Insert : Trigger that executes due to an insert operation and before the record is saved to the database it is a before Insert trigger
  • Before Update : Trigger that executes due to an update operation and before the record is saved to the database it is a before update trigger
  • Before Delete : Trigger that executes due to a delete operation and before the record is saved to the database it is a before delete trigger
  • After Insert :Trigger that executes due to an insert operation but after the record is saved to the database it is an after Insert trigger
  • After Update : Trigger that executes due to an update operation and after the record is saved to the database it is an after update trigger
  • After Delete : Trigger that executes due to a delete operation and after the record is deleted from the database it is an after delete trigger
  • After Undelete : Trigger that executes due to a undelete operation and after the record is undeleted from the database it is an after undelete trigger              
Trigger Context Variables:
VariableUsage
isExecutingReturns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an execute anonymous() 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 theAPI.)
newReturns a list of the new versions of the sObject records.
Note that this sObject list is only available in insert and update triggers, and the records can only be modified in before triggers.
newMapA map of IDs to the new versions of the sObject records.
Note that this map is only available in before update, after insert, and after update triggers.
OldReturns a list of the old versions of the sObject records.
Note that this sObject list is only available in update and delete triggers.
oldMapA map of IDs to the old versions of the sObject records.
Note that this map is only available in update and delete triggers.
SizeThe total number of records in a trigger invocation, both old and new.
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
beforeinsertAllowed.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.
afterinsertNot allowed. A runtime error is thrown, as trigger.newis already saved.Allowed.Allowed, but unnecessary. The object is deleted immediately after being inserted.
beforeupdateAllowed.Not allowed. A runtime error is thrown.Not allowed. A runtime error is thrown.
afterupdateNot allowed. A runtime error is thrown, as trigger.newis 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.
beforedeleteNot 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.
afterdeleteNot 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.
afterundeleteNot allowed. A runtime error is thrown. trigger.old is not available in after undelete triggers.Allowed.Allowed, but unnecessary. The object is deleted immediately after being inserted.
Order of execution of triggers in Salesforce environment:                 
  • Old record loaded from database (or initialized for new inserts)
  • New record values overwrite old values
  • System Validation Rules
  • All Apex “before” triggers
  • User Validation Rules
  • Record saved to database (but not committed)
  • Record ID and System generated fields are generated.
  • Record reloaded from database.
  • All Apex “after” triggers
  • Assignment rules
  • Auto-response rules
  • Workflow rules
  • Escalation rules
  • Parent Rollup Summary Formula value updated (if present)
  • Database commit
  • Post-commit logic (sending email)

No comments:

Post a Comment

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC)

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC) Introduction: Salesforce Lightning Web ...