What is Trigger 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:

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 a 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 a 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.

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

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)
}

Trigger Context Variables

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. The following table gives a list of context variables and their usage:

Context VariableUsage
isInsertReturns true if the trigger was fired due to an insert operation
isUpdateReturns true if the trigger was fired due to an update operation
isDeleteReturns true if the trigger was fired due to a delete operation
isBeforeReturns true if the trigger has been fired before any record was saved
isAfterReturns true if the trigger was fired after all records have been saved
isUndeleteReturns true if the trigger was fired after a record has been recovered from the Recycle Bin
newReturns a list of new versions of the sObject records
newMapA map of IDs to the new versions of the sObject records
oldReturns a list of old versions of the sObject records
oldMapA map of IDs to the old versions of the sObject records
sizeThe 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 loop.

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

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 which 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 which 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 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!

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!

Recommended Videos

Leave a Reply

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