Triggers in Salesforce

Salesforce is a leading customer relationship management (CRM) platform. It provides a platform for sales, service, IT, commerce, and marketing teams to connect with their customers and partners. It helps the users to track customer analytics, customer complaints, success, and a variety of CRM functions. As it operates on the cloud, users will be able to access it from anywhere and everywhere. Salesforce and Apex share a multitenant environment. Salesforce has a set of triggers available. In this post, we will explain in detail what triggers are, what are its types, and how to write them. You will also get a detailed understanding of the context variables that can be used in triggers. Let us get started.

What are the triggers in Salesforce?

Apex is one of the many programming languages that Salesforce uses to perform actions. Since the Salesforce triggers are built with Apex code, they are also called Apex triggers. An action that needs to be performed before or after data manipulation language (DML) events occurs is called a trigger. The Salesforce triggers are used to trigger Apex code before or after changes to Salesforce records like insertions, updates, or deletions.

The Salesforce triggers help in defining custom actions on the data. They are used to perform operations based on specific conditions. We can define triggers for top-level standard objects like contact, account, custom objects, standard child objects, and custom objects. When we create triggers, they will be active by default. So, when a database event occurs, the Salesforce will fire the active triggers automatically. Triggers will be helpful when we can't perform some tasks with point-and-click tools in the Salesforce user interface. 

For instance, we can set a trigger to run after records have been deleted, or when a record is restored from the recycle bin, or before inserting an object's records.

Types of triggers

The triggers in Salesforce are mainly of two types - before and after triggers.

Before triggers 

When we want to update or validate record values before saving them to a database, we can run a before trigger. We can set a before trigger before a record is inserted, updated, or deleted. 

After triggers 

The after triggers are used to access field values that are set by the system and to affect the changes in the records. The records that fire after triggers will be in read-only mode. This trigger is used when a record is inserted, updated, or deleted. The records that have a relationship with the trigger fired record will get modified.

Bulky Triggers

All triggers in Salesforce are referred to as bulky triggers as they operate on multiple records at a time. Bulky triggers will be able to handle both bulk operations and single record based operations. Here are the operations that the bulky trigger handles.

Data import

  • Lightning Platform Bulk API calls
  • Mass actions like record owner deletes and updates
  • Recursive Apex methods and triggers that invoke bulk DML statements

Salesforce Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Syntax of triggers

Here is the syntax for defining a Salesforce trigger,

trigger TriggerName on ObjectName (TriggerEvents) {


                     <code block>

                    }


The TriggerEvents can be of the following events.

  • Before insert
  • Before update
  • Before delete
  • After insert
  • After update
  • After delete
  • After undelete

We can use multiple trigger events in a single trigger by giving them in a list separated by commas. Here is an example of a trigger.


trigger AccountTrigger on Account (before insert, before delete) {

    <code block>

}


Here are a few points that will help you while working with triggers.

  • We should not use the static keyword inside the code block. 
  • We don't have to commit changes made by a trigger to a database manually. 
  • On successful completion of a trigger, the database changes will get committed automatically. 
  • If a trigger has failed, any database changes will be rolled back.

Context variables in triggers

Salesforce provides some implicit variables that can be defined by triggers to access run-time context. These context variables will be available in the System.Trigger class.

Variable Usage
isExecuting If the current context for the Apex code is a trigger, it returns true.
isInsert If the trigger is fired because of an insertion operation from the Apex, API, or Salesforce UI, it returns true.
isUpdate If the trigger is fired because of an update operation from the Apex, API, or Salesforce UI, it returns true.
isDelete If the trigger is fired because of a delete operation from the Apex, API, or Salesforce UI, it returns true.
isBefore If a trigger is fired before a record is saved, it returns true.
isAfter If a trigger is fired after a record is saved, it returns true
isUndelete If a trigger is fired after a record is undeleted i.e., recovered from the recycle bin, it returns true. The undelete operation can be fired from Apex, API, or Salesforce UI.
new This variable is only available for insert, update, and undelete triggers and records can be modified for before triggers. It returns the list of new versions of the sObject records.
newMap This variable is only available for before update, after insert, after update, and after undelete triggers. It returns a map of IDs to the new versions of the sObject records.
old This variable is only available for update and delete triggers and records. It returns the list of old versions of the sObject records.
oldMap This variable is only available for update and delete triggers. It returns a map of IDs to the old versions of the sObject records.
operationType It returns an enum of type System.TriggerOperation of the current operation. The values of enum are the trigger events.
size It returns the number of old and new records in a trigger invocation.

Context variable considerations

Here are a few considerations to be aware of to trigger context variables.

  • We cannot use trigger.new and trigger.old in Apex DML operations.
  • With trigger.new, we can use an object to change its own field values in before triggers. The trigger.new will not get saved in after triggers, so it will result in a runtime exception.
  • The trigger.old context variable will always be read-only.
  • We cannot delete the trigger.new context variable.

The following table depicts the considerations of actions for different trigger events.

Subscribe to our youtube channel to get new updates..!

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. When no original object is created, we won't have anything to update. Not applicable. When no original object is created, we won't have anything to update.
after insert Not allowed. As trigger.new is already saved, a runtime error will be thrown. Allowed Allowed, but not necessary. The object will be 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. As trigger.new is already saved, a runtime error will be thrown. Allowed. If there is an infinite recursion, the governor limits will find the error. Allowed. The updates will be saved to the object before it is deleted. So if the object is recovered (undeleted), the changes become visible.
before delete Not allowed. As trigger.new is not available in before delete triggers, a runtime error will be thrown. Allowed. The updates will be saved to the object before it is deleted. So if the object is recovered (undeleted), the changes become visible. Not allowed. As deletion is already in progress, a runtime error will be thrown.
after delete Not allowed. As trigger.new is not available in after delete triggers, a runtime error will be thrown. Not applicable as the original object has already been deleted. Not applicable as the original object has already been deleted.
after undelete Not allowed. A runtime error will be thrown. Allowed. Allowed, but not necessary. The object will be deleted immediately after being inserted.

Salesforce Training

Weekday / Weekend Batches

Conclusion

Triggers are an important concept in Salesforce for both developers and admins. They ease the work of developers, administrators, and salespeople by managing records effectively. When you write Apex triggers, you have to keep in mind that the code should support bulk operations. There is a chance to prevent DML operations from occurring with the help of the addError() method. The custom error message will get displayed in the application interface when exceptions are used in Trigger.new records in insert and update triggers, and on Trigger.old records in delete triggers. If any trigger in the database throws an unhandled exception, all the records will be marked with an error. There won't be any further processing tasks executed on the error records. It will be difficult to understand all the triggers at once. But when you practice enough, you will find that the triggers are the best and easy way to perform some operations efficiently and accurately.

Categories

Request for more information

Mudassir
Mudassir
DevOps ERP and IAM tools
Mudaasir is a programming developer for hkr trainings. He has a well knowledge of today’s technology and I’ve loved technology my entire life. And also been lucky enough to work for the programmer including science and technology. Big thanks to everyone who has followed me on LinkedIn and twitter.

WhatsApp
To Top