top of page

Triggers in Salesforce | Salesforce development interview questions

Updated: May 19, 2023




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

A trigger in Salesforce is an Apex code used to perform an operation before or after a record is operated.

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

}


2. What are the two types of triggers 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.


3. What is the use of trigger class in Salesforce?

· allow you to perform various actions

· help you automate your processes,

· improve your data management, and solve complex scenarios


4. What are different events available in Triggers?

A trigger is a set of statement which can be executed on the following events. In above trigger events one or more of below events can be used with comma-separated.


Here is a list of trigger events in salesforce


before insert

before update

before delete

after insert

after update

after delete

after undelete


5. Best practice and consideration for Trigger?


1) One Trigger Per Object


Always prefer to have one trigger per object. In case of multiple triggers per object, you don’t have control over the order of execution for triggers.


2) Logic-less Triggers


Avoid writing logic/method in the trigger. Logic/method written inside trigger cannot be exposed to other class. Thus, it decreased code reusability and not able to write test class properly.


3) Context-Specific Handler Methods


Create context-specific handler methods in Trigger handlers like afterInsertLogic, beforeInsertLogic etc.


4) Bulkify your Code


Always prefer to Bulkify your trigger code. It should work as designated when there are more than one record.


5) Avoid using DML statements and SOQL Queries inside FOR Loops


A single Apex transaction gets a maximum of 100 SOQL queries before exceeding the governor limit. So, if the trigger is invoked by a batch of more than 100 records, the governor limit will throw a runtime exception. Also, try to query related objects in one single query.


6) Using Collections, Streamlining Queries, and Efficient For Loops


It is important to use Apex Collections to efficiently query data and store the data in memory. A combination of using collections and streamlining SOQL queries can substantially help writing efficient Apex code and avoid governor limits.


7) Querying Large Data Sets


The total number of records that can be returned by SOQL queries in a request is 50,000. If returning a large set of queries causes you to exceed your heap limit, then a SOQL query for loop must be used instead. It can process multiple batches of records through the use of internal calls to query and query more.


8) Use @future Appropriately


It is essential to write down your Apex code with efficiency handle bulk or many records at a time. Use @fututre just in case of a call out from trigger to make sure the current transaction should not have to wait for a call out response.


9) Avoid Hardcoding IDs


When deploying Apex code between different environments or Sandbox, or installing Force.com AppExchange packages, it is essential to avoid hardcoding any kind of value such as IDs in the Apex code. If possible, use custom label/custom setting to store such hardcoded values.


10) Avoid calling batch from Trigger


When a batch is called from Trigger there are high chances to hit the governor limit provided by Salesforce.


6. Difference between Validation rules and Triggers?


Apex Trigger


Apex Triggers in Salesforce enables user to perform custom actions before or after changes to records. Similar to other database triggers, Apex Triggers can be programmatically configured to execute the following operations.


Insert.

Update.

Delete.

Merge.

Upsert.

Undelete.


In Salesforce, triggers are of two types they are


Before Triggers :- Before Triggers are used to validate records before updated to database

After Triggers :- After Triggers are used to access field values like Id or LastModiefiedDate.

Validation Rules.


Validation rules in salesforce contains a formula or expressions that evaluates the data in one or more fields in a record to meet the standards and returns a vale “True” or “False” and it displays error message to the user when the Condition is “False”.


Validation Rules help enforce data integrity from both the salesforce.com UI and API.

Validation rules fire each time a record is saved and performs the validation against a certain field based upon a formula expression.

Validation rules in Salesforce are verified if the data is true , the records is saved. If the data is invalid it dispalys error message.


7. Can we call a batch job from Trigger?


Yes it is possible, we can call a batch apex from trigger but we should always keep in mind that we should not call batch apex from trigger each time as this will exceeds the governor limit this is because of the reason that we can only have 5 apex jobs queued or executing at a time.



8. What is the different between Trigger.New and Trigger.newMap?


Trigger.New


Trigger.New is a collection of records on the Object the trigger is running on. It is similar to how a developer would use List i.e. Trigger.New on Case Object would be similar to List<Case>.


When the trigger runs on a specific object, then the record or records upon which the insert, update or delete operation occurs are added to a list which can be accessed easily by using Trigger.New.


Trigger.New can be used for all event types on a trigger.


Before Insert

Before Update

After Insert

After Update


After Undelete

Example


trigger CaseTrigger on Case (before insert){

for(Case c: Trigger.New){

//iterate over list and do some action

c.Subject = 'This case is being updated by trigger logic.';

}

}


Trigger.NewMap


Trigger.NewMap extends on the Trigger.New where it contains the same records in a Map instead of a List. The map contains the ID of the record and the entire record.


It is similar to how a developer would use Map i.e. Trigger.NewMap on Case Object would be similar to Map<Id, Case>. Trigger.NewMap allows a developer to select specific records if needed.


Trigger.NewMap cannot be used in all Trigger events. It can only be used in the following:


After Insert

Before Update

After Update

After Undelete

Example


The statement will run only 1 time and fetch subject of all Cases related to the account records in the map:


trigger AccountTrigger on Account (After insert){

//use trigger.newmap to get results in a single transaction

List<Case> cLst = [Select Subject from Case where AccountId in :Trigger.NewMap.keySet()];


for(Case c: cLst ){

//iterate over list and do some action

c.Subject = 'This case is being updated by trigger logic.';

*other logic......

}

}



9. How make callout from Trigger?


Apex Trigger which makes the callout to the External system when a field in a record is updated. The Apex Trigger and the Callout method are like below


trigger updateLocation Account (after update) {

List<String> jSONBody = new List<String>();

if(trigger.isupdate)

{

set<Id> AccountIds = new Set<Id>();

list<Account> acclist = new list<Account>();

for( Id accountId : Trigger.newMap.keySet() ){

if( (Trigger.oldMap.get(accountId).Location__c != Trigger.newMap.get(accountId).Location__c))

{

AccountIds.add(accountId);

}

}

if(AccountIds.size()>0)

{

acclist = [Select id,Location__c from Account WHERE Id IN: AccountIds ];

for(Account acc : acclist)

{

handleD365Request.updSubSegJSON js = new handleD365Request.updSubSegJSON();

js.Location= acc.Location__c;

jSONBody.add(json.serialize(js));

handleReq.handleAccountReqs(jSONBody,endPoint);

}}


Apex Class with future method


@future (callout=true)

public static void handleAccountReqs(List<String> jsonBody,String endPoint) {

...............

for (String str : jsonBody)

{

Http http1 = new Http();

HttpRequest req1 = new HttpRequest();

String d365EndPoint = resource + endPoint;

req1.setMethod('POST');

req1.setTimeout(20000);

req1.setHeader('Authorization','Bearer '+bearerToken);

req1.setEndpoint(d365EndPoint);

req1.setBody(str);

req1.setHeader('Content-Type', 'application/json;charset=UTF-8');

HttpResponse res1 = http1.send(req1);

}

}


10. Have you used any trigger framework in Salesforce?

OR

Type Of Apex Trigger Frameworks In Salesforce?


There are different trigger frameworks available in the market for Salesforce but in this post, we will talk about them.


1. Trigger Handler Pattern

2. Trigger Framework using a Virtual Class

3. Trigger Framework using an Interface

4. An architecture framework to handle triggers


#1 Trigger Handler Pattern


Please check this post to learn about Handler pattern and code. Let’s talk about what is the advantage of the Trigger Handler Patter.

1. Apex Class that handles trigger logic

2. Allows code to be called from other code or tests

3. Uses specific Trigger contexts and Trigger variables for routing

4. Keep Triggers Simple

5. Allow for greater flexibility

6. Make code reusable

7. Unit tests are much easier



#2 Trigger Framework Using A Virtual Class

Please check this post to learn more about Virtual Class Trigger Framework. This trigger framework bundles a single TriggerHandler base class that you can inherit from in all of your trigger handlers. The base class includes context-specific methods that are automatically called when a trigger is executed


Trigger Framework using a Virtual Class

Accomplishments with this Trigger framework :-


1 line trigger

Only need to add handler methods that we want to use

All routing is handled for us



#3 Trigger Framework Using An Interface

Please check this post to learn about this framework.



Trigger Framework using an Interface

Accomplishments with this Trigger framework :


1 line trigger

All routing is handled for us

All handlers are consistent and will have the same methods

Multiple ways to deactivate a trigger


#4 An Architecture Framework To Handle Triggers

Please check this post to learn about this framework.


An architecture framework to handle triggers

Accomplishments with this Trigger framework :-


One line trigger

All routing is handled for us

Establish all methods while letting us pick and choose which ones we want

Individual event handler methods



11. How make callout from Trigger?


Apex Trigger which makes the callout to the External system when a field in a record is updated. The Apex Trigger and the Callout method are like below


trigger updateLocation Account (after update) {

List<String> jSONBody = new List<String>();

if(trigger.isupdate)

{

set<Id> AccountIds = new Set<Id>();

list<Account> acclist = new list<Account>();

for( Id accountId : Trigger.newMap.keySet() ){

if( (Trigger.oldMap.get(accountId).Location__c != Trigger.newMap.get(accountId).Location__c))

{

AccountIds.add(accountId);

}

}

if(AccountIds.size()>0)

{

acclist = [Select id,Location__c from Account WHERE Id IN: AccountIds ];

for(Account acc : acclist)

{

handleD365Request.updSubSegJSON js = new handleD365Request.updSubSegJSON();

js.Location= acc.Location__c;

jSONBody.add(json.serialize(js));

handleReq.handleAccountReqs(jSONBody,endPoint);

}}


Apex Class with future method


@future (callout=true)

public static void handleAccountReqs(List<String> jsonBody,String endPoint) {

...............

for (String str : jsonBody)

{

Http http1 = new Http();

HttpRequest req1 = new HttpRequest();

String d365EndPoint = resource + endPoint;

req1.setMethod('POST');

req1.setTimeout(20000);

req1.setHeader('Authorization','Bearer '+bearerToken);

req1.setEndpoint(d365EndPoint);

req1.setBody(str);

req1.setHeader('Content-Type', 'application/json;charset=UTF-8');

HttpResponse res1 = http1.send(req1);

}

}


12. Order of execution for Trigger


Order Of Execution


Here is cheat-sheet of Order of execution. Salesforce performs the following events in below order.


1. Loads Initial record.

2. If the request came from a standard UI edit page, Salesforce runs system validation to check the record for page layout-specific rules, field definition, and Maximum field length.

3. Executes before record-triggered flows.

4. Executes all before triggers.

5. Runs most Custom validation.

6. Executes duplicate rules.

7. Saves the record to the database, but doesn’t commit yet.

8. Executes all after triggers.

9. Assignment rules.

10. Executes auto-response rules.

11. Executes workflow rules. If there are workflow field updates,

12. updates the record again.

13. Due to Workflow field updates introducing new duplicate field values, executes duplicate rules again.

14. If the record was updated with workflow field updates, fires before update triggers and after update trigger one more time (and only one more time), in addition to standard validations. Custom validation rules are not run again.

15. Escalation rules.

16. Executes these Salesforce Flow automations

17. Processes

18. Flows launched by processes

19. Flows launched by workflow rules (flow trigger workflow actions pilot)

20. Executes record-triggered flows that are configured to run after the record is saved.

21. Executes entitlement rules.

22. If the record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the parent record. Parent record goes through save procedure.

23. If the parent record is updated, and a grandparent record contains a roll-up summary field or is part of a cross-object workflow, performs calculations and updates the roll-up summary field in the grandparent record. Grandparent record goes through save procedure.

24. Executes Criteria Based Sharing evaluation.

25. Commits all DML operations to the database.

26. Executes all after-commit logic.

27. sending email.

28. asynchronous Apex jobs

29. Asynchronous paths in record-triggered flows


13. When we should use Trigger.Old


Trigger.old returns List of old records which are updated with new values. These List of records already there in Database. Trigger.old available in Before update, after update, Before Delete and After Delete triggers.

Returns a list of the old versions of the sObject records. Note that this sObject list is only available in update and delete triggers.



14. What is Trigger Handler pattern?


Trigger Handler Pattern


Advantage of the Trigger Handler Patter.


  • Apex Class that handles trigger logic

  • Allows code to be called from other code or tests

  • Uses specific Trigger contexts and Trigger variables for routing

  • Keep Triggers Simple

  • Allow for greater flexibility

  • Make code reusable

  • Unit tests are much easier







Comments


bottom of page