Page Contents
Apex Triggers in Salesforce
Apex Triggers in Salesforce
What is Triggers in Salesforce?
A trigger is an Apex script that executes before or after data manipulation language (DML) events occur. Apex triggers enable you to perform custom actions before or after events to record in Salesforce, such as insertions, updates, or deletions. Just like database systems support triggers, Apex provides trigger support for managing records.
When to use salesforce triggers
We should use triggers to perform tasks that can’t be done by using the point-and-click tools in the Salesforce user interface. For example, if validating a field value or updating a field on a record, use validation rules and workflow rules instead.
What is Trigger Syntax?
trigger TriggerName on ObjectName (trigger_events) { code_block }
Trigger events in salesforce?
A trigger is a set of statement which can be executed on the following events. In above trigger events one or more of below events can be used with comma-separated.
Here is a list of trigger events in salesforce
- before insert
- before update
- before delete
- after insert
- after update
- after delete
- after undelete
What are different type of Triggers?
There are two types of triggers:
- Before triggers are used to perform a task before a record is inserted or updated or deleted. These are used to update or validate record values before they are saved to the database.
- After triggers are used if we want to use the information set by Salesforce system and to make changes in the other records. are used to access field values that are set by the system (such as a record’s Id or LastModifiedDate field), and to affect changes in other records. The records that fire the after trigger are read-only.
What are the considerations while implementing the Triggers?
Consider the following before implementing the triggers.
- Upsert trigger fires on 4 different events :- before(insert, update), after (insert, update)
- Merge trigger are fired on both events on delete
- Field history is updated after the trigger has successfully finished processing data.
- Any callout should be asynchronous so that trigger does not have to wait for the response.
- A trigger cannot have a static keyword in its code.
- If a trigger completes successfully the changes are committed to the database and if it fails the transaction is rolled back.
Read the Apex Developer Guide for more detailed considerations.
What are context variables in triggers?
All triggers define implicit variables that allow developers to access run-time context. These variables are contained in the System.Trigger class.
Here is list of context variables in triggers
- isExecuting: Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
- isInsert: Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.
- isUpdate: Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.
- isDelete: Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.
- isBefore: Returns true if this trigger was fired before any record was saved.
- isAfter: Returns true if this trigger was fired after all records were saved.
- isUndelete: Returns 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 the API.)
- new: Returns a list of the new versions of the sObject records. This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified in before triggers.
- newMap: A map of IDs to the new versions of the sObject records. This map is only available in before update, after insert, after update, and after undelete triggers.
- old : Returns a list of the old versions of the sObject records. This sObject list is only available in update and delete triggers.
- oldMap: A map of IDs to the old versions of the sObject records. This map is only available in update and delete triggers.
- size: The total number of records in a trigger invocation, both old and new.
Refer to Trigger context variables in salesforce link for more details.
Context Variable Considerations
Trigger Event | Can change fields using trigger.new | Can update original object using an update DML operation | Can delete original object using a delete DML operation |
---|---|---|---|
before insert | Allowed. | 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. |
after insert | Not allowed. A runtime error is thrown, as trigger.new is already saved. | Allowed. | Allowed, but unnecessary. The object is deleted immediately after being inserted. |
before update | Allowed. | Not allowed. A runtime error is thrown. | Not allowed. A runtime error is thrown. |
after update | Not allowed. A runtime error is thrown, as trigger.new is 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. |
before delete | Not 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. |
after delete | Not 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. |
after undelete | Not allowed. A runtime error is thrown. | Allowed. | Allowed, but unnecessary. The object is deleted immediately after being inserted. |
Salesforce Trigger Example
before insert trigger salesforce
Account trigger to set account rating as ‘Hot’ if account industry is ‘Banking’ or ‘Healthcare’
before update trigger salesforce
trigger AccountCustomTrigger on Account (before insert, before update) { for(Account acc : Trigger.New) { if(acc.Industry != null && (acc.Industry == 'Banking' || acc.Industry == 'Healthcare')){ acc.Rating = 'Hot'; } } }
Please note that in the above example we are not manually updating accounts using DML statement as it is before insert or before update trigger.
after insert trigger salesforce
Let us see one more example of a trigger on contact which will create Account record whenever contact is created without an account.
trigger ContactCustomTriggerExample on Contact (after insert) { List<Account> accListToInsert = new List<Account>(); for(Contact con : Trigger.New) { //check if account is null on contact if(con.AccountId == null ) { Account acc = new Account(); //Add all required field on Account acc.Name = con.LastName; acc.Phone = con.Phone; accListToInsert.add(acc); } } if(!accListToInsert.isEmpty()){ insert accListToInsert; } }
Define Recursive Trigger and how to avoid it?
There is a possibility that the result of the trigger can end up calling the same trigger again and can run in a loop, this is known as a recursive trigger. To avoid this scenario we should create a static variable and check the value of this variable before we execute anything in the trigger. For more details refer to below link:
Avoid recursive trigger in salesforce
What do you mean by the bulkifying trigger?
A trigger should be able to handle single record and thousands of record. There are two important point for bulkifying trigger:
- Write triggers that operate on collections of sObjects.
- Write triggers that perform efficient SOQL and DML operations.
If we will not follow above point we may hit governor limit when records are created/updated/deleted in mass using data loader or other tool.
For more detail about trigger in salesforce refer Official link
For interview questions related to salesforce refer to Salesforce Interview Questions on Triggers
5 comments
Skip to comment form
Hey ContactCustomTriggerExample is written on Account. I believe it should be on Contact.
Thanks,
Vamsy M
Good one Ankush, your article is really good.
Can you provide few more examples on custom objects triggers
Hey Man, such a great explanation. Keep going
Create a Permission field in Contact object then do the following
If Permission on the Contact object is True based on the permission field, records in account should not edit it should be read only.
If false record in Account should edit. This is to be done using trigger .
***records you need to restrict is in account,
restrict to edit and read only.
can someone help me with this