Salesforce Triggers

Ranbir Kumar Das
Salesforce Champion
4 min readAug 16, 2021
salesforce Triggers

A Salesforce trigger is an apex script that runs before or after a data manipulation language (DML) event occurs. Adding new records to your sales force, deleting old records from a sales force database, updating records within your sales force, or generally manipulating data through the system are examples of data manipulation language events.

Apex triggers enable you to perform tasks you can’t complete using the point-and-click user interface in Salesforce.

Apex triggers are designed to allow you to run custom actions either before or after a data manipulation event has taken place. In Apex scripts, data manipulation is triggered either before or after the apex scripts are written in Apex.

There are two different types of Apex triggers within Salesforce:

  • “Before” Apex Triggers. You use these to update and validate the value in a record before saving it to Salesforce.
  • “After” Apex Triggers. They provide access to record values and allow you to use those values to change records in your Salesforce database. An “After” trigger is read-only, in contrast to “Before” triggers.

The following is how an Apex Trigger script is written:

Trigger trigger Name on Object(Trigger event)
{
//logic here}

There are many actions you can take within Salesforce to trigger Apex triggers, including:

  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete

Context variable

You can access the records that caused the trigger to the fire by using context variables.

In other circumstances, context variables indicate whether a trigger was triggered by an update or some other event. Triggers that combine multiple events can use these variables.

isInsert

Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.

isUpdate

Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.

isInsert

Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or the API.

isUpdate

Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or the API.

isDelete

Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or the API.

isBefore

Returns true if this trigger was fired before any record was saved.

isAfter

Returns true if this trigger was fired after all records were saved.

isUndelete

Returns true if this trigger was fired after a record is recovered from the Recycle Bin. This recovery can occur after an undelete operation from the Salesforce user interface, Apex, or the API.

new

Returns a list of the new versions of the sObject records.

This sObject list is only available in insert, update, and undelete triggers, and the records can only be modified before triggers.

size

The total number of records in a trigger invocation, both old and new.

old

Returns a list of the old versions of the sObject records. This sObject list is only available in update and deletes triggers.

trigger ContextExampleTrigger on Account (before insert, after insert, after delete) {if (Trigger.isInsert) { if (Trigger.isBefore) {  // Process before insert } else if (Trigger.isAfter) {  // Process after insert }} else if (Trigger.isDelete) { // Process after delete }}

Trigger (Not bulkify)

trigger AccountUpdate on Account (before update,before insert,after update) {if(Trigger.isUpdate){if(Trigger.isBefore){Account a=Trigger.New[0];a.Rating =’Hot’;}}// — — — -print the single related contactif(Trigger.isUpdate){if(Trigger.isAfter){List<Contact> x=[select id,email from Contact WHERE AccountId =:Trigger.new[0].id];system.debug(x);}}// — — — — — — — — — — updated the single contactif(Trigger.isUpdate){if(Trigger.isAfter){List<Contact> x=[select id,email from Contact WHERE AccountId =:Trigger.new[0].id];contact c= new contact();c.id=x[0].id;c.firstname=’veer-updated-trigger’;update c;}}}

Bulkify the trigger

if(Trigger.isUpdate){if(Trigger.isAfter){List<Contact> x=[select id,email from Contact WHERE AccountId =:Trigger.new];List<contact>c2=new List<contact>();for(contact c1:x){contact c= new contact();c.id=c1.id;c.firstname='veer-updated-trigger';c2.add(c);}update c2;}}

Helper Class

Writing the whole code in trigger is also not a good practice. Hence you should call the Apex class and delegate the processing from Trigger to Apex class as shown below. Trigger Helper class is the class which does all the processing for trigger.

trigger AccountUpdate on Account (before update,before insert,after update) {if(Trigger.isUpdate){if(Trigger.isAfter){triggerclass obj=new triggerclass();obj.updateclass(Trigger.new);}}}// — — — — — — — — — — Create a classpublic class triggerclass {public void updateclass(List<Account> x1){List<Contact> x=[select id,email from Contact WHERE AccountId =:x1];List<contact>c2=new List<contact>();for(contact c1:x){contact c= new contact();c.id=c1.id;c.firstname=’Updated contact’;c2.add(c);}update c2;}}

Apex Trigger Best Practices

A few best practices will make using Apex Triggers a breeze. Following these tips can reduce the learning curve for new Apex trigger users and help them avoid the mistakes they usually make.

Bulkify Your Code

When you bulkify Apex code, you can efficiently process multiple records at a time. When a collection of records initiates Apex, a single instance of that code is executed. It should have been able to handle all of the records that were a part of that collection, but that’s not the case.

Avoid SOQL Queries or DML statements inside FOR Loops

Using for loops when using Apex Triggers is a common mistake. The Governor enforces a limit on the number of SOQL queries, which causes issues. Another governor limit affects the amount of DML statements — such as inserts, updates, deletes, and undeletes.

These statements should be outside of loops.

One trigger per object

Bulkify your Trigger

Use context variables

Avoid SOQL inside the for loop

Avoid Hard Coded IDs

Avoid complex logic inside a trigger. Use classes (Helper classes).

Use collection

--

--

Ranbir Kumar Das
Salesforce Champion

I M Believer, Helper, Chaser, Thinker, Rich, Explorer, Prayer, Boss, Freedom, Fearless, Investor, Faith, Creator, trillionaire, CSM, Salesforce certified