• Articles
  • Tutorials
  • Interview Questions

Triggers in Salesforce - Apex Trigger Salesforce

Table of content

Show More

What are Triggers in Salesforce?

In Salesforce, triggers are referred to as Apex Triggers. These are distinct and available specifically for common and expected actions like lead conversions.

Check out this YouTube Video on Salesforce Tutorial for beginners:

Video Thumbnail

A trigger in Salesforce is an Apex code used to perform an operation before or after a record is operated. These operations can be one of the following:

What Is Trigger in Salesforce

There are primarily two types of Apex Triggers:

  • Before Trigger: This type of trigger in Salesforce is used either to update or validate the values of a record before they can be saved into the database. So, basically, the before trigger validates the record first and then saves it. Some criteria or code can be set to check data before it gets ready to be inserted into the database.
  • After Trigger: This type of trigger in Salesforce is used to access the field values set by the system and affect any change in the record. In other words, the after trigger makes changes to the value from the data inserted in some other record.

Become a Salesforce Expert

Bulky Triggers

All triggers in Salesforce are, by default, bulky triggers, i.e., you can process multiple records at a time. Bulky triggers can handle not only bulk operations but also the following single-record updates:

  • Importing data
  • Mass actions
  • Bulk API calls
  • Recursive Apex methods and triggers invoke 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 now discuss the various keywords used in the syntax:

  • triggerName is the name you want to give to your trigger.
  • Objectname is the object on which the action needs to be performed.
  • Trigger_events are the comma-separated list of one or more events such as:
    • Before insert: When using this event, the code block is executed before a new record is inserted.
    • Before update: When you use this event, the code gets executed before a new record is updated in the object.
    • Before delete: When you’re using this event, the record gets deleted before the execution of the code block.
    • After insert: Here, the code block gets executed first, and then the insertion of the record is done.
    • After update: In this event, the updating of a record is done after the execution of the code block.
    • After delete: When you’re using this event, you are able to delete a record after the execution of the code block.
    • After undelete: This event is used when the record that was sent to the Recycle Bin needs to be restored.

Example:

The following piece of code will help you understand how to create an object and how to create a trigger in Salesforce.

trigger tname on contact(before insert)
{ contact c = new contact();
if (c.email==null)
}

Types of Triggers

There are two different types of triggers, which are mentioned below:

  1. Before Triggers: Before Triggers are used to perform tasks before records are inserted, updated, or deleted. Record values can be updated or validated using this type of trigger before the values are saved to the database.
  2. After Triggers: Triggers are used if the information set by the Salesforce system needs to be used or changed in other records that need to be made. The records that fire this type of trigger are read-only.

Get 100% Hike!

Master Most in Demand Skills Now!

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 are context variables in triggers?

All triggers in Salesforce determine implicit variables that enable developers to access the runtime context so that they don’t need to define objects from their side. To access the records that caused the trigger to fire, context variables are used.

Trigger Context Variables

The following table gives a list of context variables and their 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 of these variables are used as ‘Trigger.variable.’ For the following piece of code, in the second line, you can see how the variable ‘new’ is used as ‘Trigger.new.’ It gives a list of the sObjects that can be iterated over in a for loop.

variable new

Using Trigger Exceptions

Sometimes restrictions need to be added to certain database operations. To prevent DML operations from occurring, triggers can be used by calling the ‘addError()’ method on a record or field. A custom error message is displayed in the application interface and logged when triggers are used on Trigger.new records in insert and update triggers and on Trigger.old records in delete triggers.

If errors are added to before triggers, there is a lesser delay in response time.

A subset of the records that are being processed can be marked with the ‘addError()’ method:

  • If the trigger was generated by a DML statement in Apex, a single error will result in the entire operation rolling back. The runtime engine, however, still processes every record in the operation for compiling a detailed list of errors.
  • If a bulk DML call in the Lightning Platform API generates the trigger, the runtime engine sets aside the bad records and tries to perform a partial save of the records that did not generate any errors.

If an unhandled exception is thrown by a trigger, all the records are marked with an error, and there is no further processing.

Triggers in Salesforce Vs. Workflows in Salesforce

You learned about Salesforce Workflows in our previous section. Now, when you are learning about triggers, there is a chance for you to get confused between workflows and triggers in Salesforce.

Let me sort this out for you. Well, if Salesforce has created two different products, it is obvious that there would be a huge difference between them. Now, what is the difference?

Salesforce Workflow:

  • It is an automated process that can shoot an action based on the evaluation and rule criteria.
  • Performing DML operations in the workflow is not possible.
  • You can obtain a workflow over an object.
  • You can’t create a query from the database.

Salesforce Trigger:

  • It is a piece of code that is executed either before or after a record is updated or inserted.
  • More than 15 DML operations can be used in a single trigger.
  • More than 20 SOQLs can be used from the database in a trigger.
  • You can access triggers across an object and related to that object.

Limitations of Workflows That Triggers in Salesforce Overcome

  • Workflows cannot create or update a separate object.
  • You can’t reference certain fields when using workflows.
  • You will not have your workflow doing more than just field updates and emails.

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 is a recursive trigger and how to avoid it?

A recursive trigger occurs when a trigger execution leads to the triggering of the same trigger again, which creates an infinite loop. 

To avoid this, you can follow a few practices. 

Firstly, review your trigger logic to identify any potential recursive scenarios. 

Secondly, use static variables or flags to track the trigger execution and prevent retriggering. Lastly, ensure that the trigger is designed to handle bulk data processing to minimize the chances of recursive calls. 

By implementing these precautions, you can avoid recursive triggers effectively.

What is a Bulkifying Trigger?

A trigger should be able to handle a single record as well as thousands of records. The following two important points must be kept in mind when dealing with bulkifying triggers:

  • Write triggers that work on collections of sObjects
  • Write triggers that perform efficient SOQL and DML operations

Not following the above point may result in a governor limit when records are mass-created, updated, or deleted using a data loader or other tool.

Conclusion

This is all about triggers in Salesforce. I hope that it helped you and gave you a very precise idea of what a trigger actually is in Salesforce. In the next tutorial section, you will learn about Salesforce Lightning. Stay tuned!

 

Course Schedule

Name Date Details
Salesforce Certification 30 Nov 2024(Sat-Sun) Weekend Batch View Details
07 Dec 2024(Sat-Sun) Weekend Batch
14 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Salesforce Certified Professional

Rahul is a seasoned Salesforce Certified administrator and app builder with 10+ years of experience in many Salesforce technologies, such as Salesforce CRM and business process automation. In his free time, he likes to write and read about the latest technologies.