What are Triggers in Salesforce?

Triggers in Salesforce are called Apex Triggers. These are distinct and are available specifically for common and expected actions like lead conversions.

Before going deep into knowing what a trigger is, have a look at the topics you will learn in this section:

Check out this YouTube Video on Salesforce Tutorial for beginners:

Triggers in Salesforce - Salesforce Apex Triggers

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

What Is Trigger in Salesforce

There are primarily two types of Apex Triggers:

  • Before Trigger: This type of trigger in Salesforce is used to either 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 in 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 bulk operations and single-record updates such as:

  • Importing data
  • Mass actions
  • Bulk API calls
  • Recursive Apex methods and triggers invoke bulk DML statements

Get familiar with the Top Salesforce Admin Interview Questions to get a head start in your career!

Trigger Syntax

The syntax of a trigger is very simple. Let’s first look at its basic syntax:

trigger triggerName on Objectname(trigger_events)
{
//code_block
}

Let’s now discuss 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)
}

Learn about configuring, price, and quote in our blog on Salesforce CPQ!

Types of Triggers

There are two different types of triggers:

  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: After 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.

Writing Apex Triggers

Apex Triggers allow one to perform custom actions before or after events to 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. In 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 sObjects that can be iterated over in a for a loop.

variable newCheck out the Top Salesforce Interview Questions to learn what is expected from Salesforce professionals!

Get 100% Hike!

Master Most in Demand Skills Now !

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 that is based on 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.

Check out our tutorial on Salesforce Data Types, and Field Types!

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 acc=“Select id from Account where Name=:a.Name and   Rating=:a.Rating“;
      if(acc.size()>0)
          {
          acc.Name.addError('You Cannot Create the Duplicate Account’);
          }
   }
   }

Trigger Scenario 2

This code will add a 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

This trigger 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’);
       }
  }

Do you still have queries? Come to Intellipaat’s Salesforce Community, clarify all your doubts, and excel in your career!

What is a recursive trigger and how to avoid it?

Sometimes, it can happen that the result of the trigger may call the same trigger again and result in a loop. This is known as a recursive trigger. To avoid this scenario, a static variable should be created, and the value of this variable should be checked before anything is executed in the trigger.

What is a bulkifying trigger?

A trigger should be able to handle a single record as well as thousands of records. There are  two important points that one should remember for 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 it helped you and has given you a very precise idea of what actually a trigger is in Salesforce. In the next tutorial section, you will be learning about Salesforce Lightning. Stay tuned!

Get certified in Salesforce with Intellipaat’s Salesforce Certification Training!

Course Schedule

Name Date
Salesforce Certification 2022-12-03 2022-12-04
(Sat-Sun) Weekend batch
View Details
Salesforce Certification 2022-12-10 2022-12-11
(Sat-Sun) Weekend batch
View Details
Salesforce Certification 2022-12-17 2022-12-18
(Sat-Sun) Weekend batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *