In addition, you can explore the differences between triggers and workflows, as well as grasp certain limitations of workflows that triggers address. Towards the conclusion, you’ll encounter various trigger scenarios within Salesforce.
What do Triggers do in Salesforce?
Within Salesforce, Apex Triggers are the designated term for triggers. They are unique and designed specifically for standard and anticipated operations such as lead conversions. A Salesforce trigger, written in Apex code, executes either before or after a record undergoes an operation. These operations can include:
There are primarily two categories of Apex Triggers:
- Before Trigger: This type of trigger in Salesforce is employed to either update or validate record values before they are committed to the database. Essentially, the before trigger performs validation on the record prior to saving it. Specific criteria or code can be configured to check the data before it is inserted into the database.
- After Trigger: This type of trigger in Salesforce is utilized to access field values set by the system and make modifications to the record. In simpler terms, the after trigger adjusts the value based on the data inserted in another record.
Bulk Triggers
By default, all triggers in Salesforce are considered bulky triggers, meaning they can process multiple records simultaneously. These triggers can manage not only bulk operations but also the following single-record updates:
- Data imports
- Mass actions
- Bulk API calls
- Recursive Apex methods and triggers that trigger bulk DML statements
Trigger Syntax
The syntax of a trigger is very simple. Let’s first look at its basic syntax, which is given below:
trigger triggerName on Objectname(trigger_events) { //code_block }
Let’s delve into the different keywords utilized in the syntax:
triggerName
: This is the name you choose for your trigger.Objectname
: Refers to the object where the action should take place.Trigger_events
: A comma-separated list of one or more events, including:Before insert
: Executes the code block before a new record is inserted.Before update
: Executes the code before a record is updated.Before delete
: Executes code before a record is deleted.After insert
: Executes the code block first, followed by record insertion.After update
: Updates a record after executing the code block.After delete
: Deletes a record after executing the code block.After undelete
: Restores a record from the Recycle Bin.
Example:
The code snippet below will guide you on creating an object and setting up a trigger in Salesforce.
trigger tname on contact(before insert) { contact c = new contact(); if (c.email==null) }
Types of Triggers
There are two distinct categories of triggers outlined below:
- Before Triggers: These triggers execute tasks prior to record insertion, update, or deletion. They validate or update record values before they are saved into the database.
- After Triggers: Utilized when information set by the Salesforce system must be employed or modified in other records. Records activated by this trigger type are read-only.
Writing Apex Triggers
Apex Triggers allow one to perform custom actions either before or after the events to the records in Salesforce. These actions can be insertions, deletions, or updates. Apex provides trigger support for records management.
Triggers are typically used to perform operations based on specific conditions for modifying related records or restricting certain operations from happening. Triggers can be used to do anything that can be done in Apex, including executing SOQL and DML or calling custom Apex methods.
Triggers can be used for performing tasks that can’t be done using the point-and-click tools that are in the Salesforce UI.
Triggers can be defined for top-level standard objects, such as account, contact, custom objects, and some standard child objects. When triggers are created, they are active by default. Whenever a specified database event occurs, Salesforce automatically fires active triggers..
What do context variables refer to in triggers?
In Salesforce, triggers automatically identify implicit variables, allowing developers to access the runtime context without manually defining objects. Context variables are utilized to access the records that triggered the firing of the trigger.
Variables in Trigger Context
Below is a table providing context variables along with their respective usage:
Context Variable | Usage |
isInsert | Returns true if the trigger was fired due to an insert operation |
isUpdate | Returns true if the trigger was fired due to an update operation |
isDelete | Returns true if the trigger was fired due to a delete operation |
isBefore | Returns true if the trigger has been fired before any record was saved |
isAfter | Returns true if the trigger was fired after all records have been saved |
isUndelete | Returns true if the trigger was fired after a record has been recovered from the Recycle Bin |
new | Returns a list of new versions of the sObject records |
newMap | A map of IDs to the new versions of the sObject records |
old | Returns a list of old versions of the sObject records |
oldMap | A map of IDs to the old versions of the sObject records |
size | The total number of records in a trigger invocation, both old and new |
All these variables are accessed as ‘Trigger.variable_name.’ In the code snippet below, you can observe how the ‘new’ variable is utilized as ‘Trigger.new’ in the second line. This provides a list of sObjects that can be iterated over in a for loop.
Leveraging Trigger Exceptions
Using Trigger Exceptions
There are times when certain restrictions need to be imposed on database operations. Triggers can be employed to prevent DML operations from taking place by invoking the ‘addError()’ method on a record or field. This action results in a custom error message being displayed in the application interface and logged. Such triggers are applied to Trigger.new records in insert and update triggers, and Trigger.old records in delete triggers.When errors are added to before triggers, the response time delay is reduced.The ‘addError()’ method can be applied to a subset of the records being processed:
- If the trigger is triggered by a DML statement in Apex, a single error will lead to the entire operation rolling back. However, the runtime engine still processes every record in the operation to compile a detailed error list.If a bulk DML call in the Lightning Platform API triggers the trigger, the runtime engine segregates the problematic records and attempts to partially save the records that did not encounter any errors.If an unhandled exception is thrown by a trigger, all records are marked with an error, halting further processing.
Differences Between Triggers and Workflows in Salesforce
In our previous section, you learned about Salesforce Workflows. Now, as you delve into triggers, it’s natural to encounter potential confusion between workflows and triggers in Salesforce.
Allow me to clarify this for you. When Salesforce has developed two distinct products, it’s evident that there are significant differences between them. So, what are these differences?
Salesforce Workflow:
- It’s an automated process that triggers an action based on specified evaluation criteria and rules.
- Performing DML operations within a workflow is not feasible.
- You can apply a workflow to an object.
- Creating a database query is not supported within a workflow.
Salesforce Trigger:
- It’s a code segment executed either before or after a record undergoes an update or insertion.
- A single trigger can accommodate over 15 DML operations.
- You can execute more than 20 SOQL queries from the database within a trigger.
- Triggers can be accessed across objects and are related to those objects.
Restrictions of Workflows Addressed by Triggers in Salesforce
- Workflows are unable to create or update a separate object.
- Certain fields cannot be referenced when using workflows.
- Workflows are limited to performing actions such as field updates and sending emails, and cannot perform additional operations.
Trigger Scenarios in Salesforce
You will now see three trigger scenarios in Salesforce.
Trigger Scenario 1
The following code will prevent users from creating duplicate accounts with the same names:
trigger AccountDuplicateTrigger on Account (before insert, before update) { for (Account a : Trigger.new) { List existingAccounts = [SELECT Id FROM Account WHERE Name = :a.Name AND Rating = :a.Rating]; if (!existingAccounts.isEmpty()) { a.Name.addError('You cannot create a duplicate Account.'); } } }
Trigger Scenario 2
The code mentioned below will add the prefix ‘Dr.’ to all lead names whenever a record is updated or inserted:
trigger PrefixDoctor on Lead (before insert, before update) { List leadList = Trigger.new; for (Lead l : leadList) { l.FirstName = 'Dr.' + l.FirstName; } }
Trigger Scenario 3
The following trigger code will stop users from deleting an account, as only the System Administrator has all permissions:
trigger AccountDelete on Account (before delete) { for (Account acc : Trigger.old) { acc.addError('You cannot delete the Account record.'); } }
What defines a recursive trigger, and what steps can be taken to prevent it?
A recursive trigger happens when the execution of a trigger causes the triggering of the same trigger again, resulting in an endless loop.
To prevent this, you can follow a few guidelines.
Firstly, analyze your trigger logic to detect any possible recursive situations.
Secondly, utilize static variables or flags to monitor trigger execution and avoid re-triggering. Lastly, ensure that your trigger is capable of handling bulk data processing to reduce the likelihood of recursive calls.
By implementing these measures, you can effectively prevent recursive triggers.
What does it mean for a trigger to be bulkified?
A trigger needs to manage both individual records and large collections of records. It’s crucial to remember the following key points when creating bulkified triggers:
- Develop triggers that operate on sets of sObjects.
- Implement triggers that execute efficient SOQL and DML operations.
Failure to adhere to these guidelines may lead to governor limit issues when dealing with bulk record operations like mass creation, updating, or deletion using tools like data loaders.
Summary
That’s the essence of triggers in Salesforce. I trust it provided a clear understanding of what triggers entail within Salesforce.