A trigger is the piece of code, that is executed Before or After a record is inserted or updated.

Usually, an APEX (code) based evaluation of criteria to set off a chain of events.These events execute the following types of operations like : Insert, Update, Delete, Merge, Upsert and Undelete.

Hey Guys, In this post I am going to share Salesforce Interview Questions on Triggers

1. What is a Trigger?

The trigger is defined as an Apex code that execute before or after the following functions such as insert, update and delete etc. Trigger enables to perform custom actions before and after modifications to the records of Salesforce.

Types of Apex triggers

There are two types of triggers:

• Before trigger are used to update or validate values of a record before they are saved to the database.

• After trigger are used to access field values of the records that are stored in the database and use these values to make changes in other records.

The records that fire the after trigger are read only.

Trigger Syntax


trigger TriggerName on ObjectName (trigger_events) {
 
// Implement the Logic here
code_block
}

 Example:


trigger myAccountTrigger on Account (before insert, before update) {
 
CreateAccount.getAccount();
 
}


1. myAccountTrigger – triggerName ( It is the name you would want to give your trigger).

2. Account – Objectname (It is the object on which the action needs to be performed).

3. before insert, before update – Trigger_events

Before insert: When using this event, the code block gets executed before a new record is inserted.

Before update: When you use this event, the code will get executed before a new record is updated in the object.

2. What are the various event on which a trigger can fire?

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.

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

3. What are the considerations while implementing the Triggers?

Consider the following before implementing the triggers.

• Upsert trigger fires on 4 different events :- before(insert, update), after (insert, update)

• Merge trigger are fired on both events on delete

• Field history is updated after the trigger has successfully finished processing data.

• Any callout should be asynchronous so that trigger does not have to wait for the response.

• A trigger cannot have a static keyword in its code.

• If a trigger completes successfully the changes are committed to the database and if it fails the transaction is rolled back.

4. What are context variables in triggers?

When ever a trigger is invoked it has a group of supportive variables. Which hold runtime information during the current trigger execution and these variables are known as Trigger Context Variables (TCV).

Following are the context variable available in triggers. Please note variable availability in trigger varies according to the type of trigger events.

VariableUsages
isExecutingReturns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
isInsertReturns true if this trigger was fired due to an insert operation.
isUpdateReturns true if this trigger was fired due to an update operation.
isDeleteReturns true if this trigger was fired due to a delete operation.
isBeforeReturns true if this trigger was fired before any record was saved.
isAfterReturns true if this trigger was fired after all records were saved.
isUndeleteIf a record is recovered from the recycle bin it returns trigger true.
newReturns 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.
newMapA map of IDs to the new versions of the sObject records. This map is only available in before update, after insert, after update, and after undelete triggers.
oldReturns a list of the old versions of the sObject records. This sObject list is only available in update and deletes triggers.
oldMapA map of IDs to the old versions of the sObject records. This map is only available in update and deletes triggers.
sizeThe total number of records in a trigger invocation.

5. What are the considerations while implementing the Trigger Context Variables

trigger.new and trigger.old cannot be used in Apex DML operations.

• You can use an object to change its own field values using trigger.new, but only in before triggers. In all after triggers, trigger.new is not saved, so a runtime exception is thrown.

trigger.old is always read-only.

• You cannot delete trigger.new.

6. How is Trigger.New Different from Trigger.newMap?

Trigger.New variable returns the list of sObject which has invoked the trigger and Trigger.NewMap returns the map of ID’s with the newly entered records (key & value pair). NewMap is only available in after insert, before and after the update and after undelete.

7. How is Trigger.new different from Trigger.old?

Trigger.New variable returns the list of sObject which has invoked the trigger and Trigger.old returns a list of the older versions of the records which have invoked the trigger.

Trigger.Old is only available in update and delete events.

8. Can a trigger call a batch class?

Yes, we can call a batch class in the trigger as we do in the normal apex code.

9. Can a trigger make a call to Apex callout method?

we can call a callout method in Apex Trigger but the only condition is that it has to be an asynchronous callout because the trigger flow cannot wait on the response received by the callout method.

10. What will you do if a method inside apex class need to be executed only when it is getting called from trigger?

We will use trigger.isexecuting in apex class to check if the method inside apex class is getting called from trigger and will execute the method if getting called from trigger.

11. What is the use of trigger.isexecuting?

Suppose we have a method in apex class and we want this method to run only when the method is getting called from apex trigger than we can make use of trigger.isexecuting in apex class to check if the method is getting called from trigger.

12. Is the id of record changes if we undelete a deleted record?

No, It has the same id.

13. What is a Recursive Trigger?

A recursive trigger is one that performs an action, such as an update or insert, which invokes itself owing to, say something like an update it performs.

14. How to avoid Recursive Trigger?

Recursion occurs when some code is executed again and again. It can lead to infinite loop and which can result to governor limit some time. Some time it can also result is unexpected output.

To avoid recursive triggers you can create a class with a static Boolean variable with default value true. In the trigger, before executing your code keep a check that the variable is true or not. Once you check make the variable false.

Example 1:

Apex Class: checkRecursive.apxc


public Class checkRecursive{
    private static boolean run = true;
    public static boolean runOnce(){
        if(run){
            run=false;
            return true;
        }else{
            return run;
        }
    }
}

Trigger Code: updateTrigger.apxt


trigger updateTrigger on anyObject(after update) {
    if(checkRecursive.runOnce())
    {
        //write your code here           
    }
}


Example 2:

Scenario: There is an after update trigger on account object. In the trigger, there is a date field we are checking the date is changed or not if it is changed we are doing some process.The trigger is executed five times in the transaction.

In Recursive Trigger Handler Class, we have static variable which is set to true by default.

Apex Class: ContactTriggerHandler.apxc


public class ContactTriggerHandler
{
    public static Boolean isFirstTime = true;
}

Trigger Code: ContactTriggers.apxt


trigger ContactTriggers on Contact (after update)
{
    Set accIdSet = new Set();
    if(ContactTriggerHandler.isFirstTime)
    {
        ContactTriggerHandler.isFirstTime = false;
        for(Contact conObj : Trigger.New)
        {
            if(conObj.name != 'TEST')
            {
                accIdSet.add(conObj.accountId);
            }
        }
        // any code here
    }
}

15. What do you mean by the bulkifying trigger?

By default, all triggers in Salesforce are bulky triggers. This means you can process many records simultaneously. Bulky triggers can handle bulk operations and single-record updates, such as the following :

• Data import
• Mass Fraction
• Bulk API calls
• The recursive apex methods

Note that

A trigger should be able to handle single record and thousands of record. There are two important point for it:

• Write triggers that operate on collections of sObjects.

• Write triggers that perform efficient SOQL and DML operations.

• If we will not follow above point we may hit governor limit when records are created/updated/deleted in mass using data loader or other tool.

16. Is there any limit on number of triggers define on an object?

We can define as many triggers on an object as we want but it is recommended to have one trigger per object because the order of execution of different trigger is not guaranteed and any trigger can fire first.

17. What is difference between Triggers and Workflow rules?


Triggers Workflow

• Trigger is a piece of code that executes before or after a record is inserted or updated.

• Workflow is automated process that fired an action based on Evaluation criteria and rule criteria.

• Coding is required.

• Coding is not required.

• We can access the trigger across the object and related to that objects.

• We can access a workflow across the object.

• More than 15 DML operations can be used in a single trigger.

• We cannot perform DML operation on workflow. Only insert and update.

• We can use 20 SOQL’s from data base in one trigger.

• We cannot query from database.

18. What is limitations of Workflows overcome by Triggers in Salesforce

• Workflows are not able to 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.

19. Difference between Validation rules and Triggers?

Validation Rules Triggers

Validation rules are used to confirm that the data entered into a record meet various data quality / business rules before letting the user save it.

Triggers can be used for various different things and can be executed at different times - e.g. when initiating a new record, before saving it, when a record is deleted.

Validation rules are very easy to create and virtually anyone can learn how to create these.

Triggers are more complex and generally require some development skills.

20. Differences between a Stored Procedure and a Trigger?

1. We can execute a stored procedure whenever we want with the help of the exec command, but a trigger can only be executed whenever an event (insert, delete, and update) is fired on the table on which the trigger is defined.

2. We can call a stored procedure from inside another stored procedure but we can't directly call another trigger within a trigger. We can only achieve nesting of triggers in which the action (insert, delete, and update) defined within a trigger can initiate execution of another trigger defined on the same table or a different table.

3. Stored procedures can be scheduled through a job to execute on a predefined time, but we can't schedule a trigger.

4. Stored procedure can take input parameters, but we can't pass parameters as input to a trigger.

5. Stored procedures can return values but a trigger cannot return a value.

6. We can use Print commands inside a stored procedure for debugging purposes but we can't use print commands inside a trigger.

7. We can use transaction statements like begin transaction, commit transaction, and rollback inside a stored procedure but we can't use transaction statements inside a trigger.

8. We can call a stored procedure from the front end (.asp files, .aspx files, .ascx files, etc.) but we can't call a trigger from these files.

9. Stored procedures are used for performing tasks. Stored procedures are normally used for performing user specified tasks. They can have parameters and return multiple results sets.

10. The Triggers for auditing work: Triggers normally are used for auditing work. They can be used to trace the activities of table events.

21. Why Process Builder and how is it differ from trigger?

Process builder is fully customization. No code required here because we require lengthy logic and record to complete and fulfil the requirement or if we using process builder it will take less time to complete the requirement.

It has some benefits over the trigger:

SCENARIOS OPTION REASON
Scenario I

Populate a lookup field on record update:

Traditionally required a trigger and It can be done easily with process builder.

The issue is Multi layer lookup logic- i.e. multiple / nested maps of related data required in the trigger.

Process builder

Trigger

Traditionally been something that requires a Trigger. Process builder allows administrator can do this without the use of the code.
Scenario II

Set an Account Owner based on Record criteria

Process builder

Trigger

Process builder can be used to assign ownership of records based on criteria in the object.
Scenario III

Post a chatter message based on record criteria

Process builder

Trigger

Process builder can be used to post to chatter based on record criteria.
Scenario IV

Submit a Quote for Approval when Opportunity Stage= Proposal

Process builder

Trigger

Requires 2 Processes one to Update the Quote based on the opportunity stage and another to submit the quote for the approval when the criteria on the quote had been met.
Scenario V

Launch a Flow via record criteria vs a button or link.

Process builder

Trigger

Process builder can be used to set record criteria and then launch a trigger ready flow.
Scenario VI

Clone an opportunity and change the field values

Process builder

Trigger

Although Process builder can create a new record it can’t reference any of the values from the cloned opportunity without the use of a flow to capture the opportunity values.

22. What are the best practices for Triggers?

1. Write One-Trigger Per Object

A single Apex Trigger is all you need for one particular object. If you develop multiple Triggers for a single object, you have no way of controlling the order of execution if those Triggers can run in the same contexts.

2. Logic-less Triggers

If you write methods in your Triggers, those can’t be exposed for test purposes. You also can’t expose logic to be re-used anywhere else in your org.

3. Context-Specific Handler Methods

Using specific methods in your trigger-handler-class to keep your code clean and scalable.

4. Bulkify your Code

Bulkifying Apex code refers to the concept of making sure the code properly handles more than one record at a time.

5. Avoid SOQL Queries or DML statements inside FOR Loops

An individual Apex request gets a maximum of 100 SOQL queries before exceeding that governor limit. So if this trigger is invoked by a batch of more than 100 Account records, the governor limit will throw a runtime exception.

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 queryMore

8. Use @future Appropriately

It is critical to write your Apex code to efficiently handle bulk or many records at a time. This is also true for asynchronous Apex methods (those annotated with the @future keyword). The differences between synchronous and asynchronous Apex can be found.

9. Avoid Hardcoding IDs

When deploying Apex code between sandbox and production environments, or installing Force.com AppExchange packages, it is essential to avoid hardcoding IDs in the Apex code. By doing so, if the record IDs change between environments, the logic can dynamically identify the proper data to operate against and not fail.

10. Use a Framework

A framework! Why? It will make your code conform to the best practices, better testing, scalability and cleaner.

• Follow proper naming conventions to make your code more logical and readable.

• Use trigger context-variables to identify specific event and performs tasks accordingly.

• Apex code must provide exception handling.

• Understand when to use before-trigger and when to user after-trigger.

23. What is the difference between database.insert and insert?

insert is the DML statement which is same as databse.insert. However, database.insert gives more flexibility like rollback, default assignment rules etc. We can achieve the database.insert behaviour in insert by using the method setOptions(Database.DMLOptions).

Important Difference:

insert

• Partial insert is not supported.
• Roll back is not supported.
• If we use the DML statement (insert), then in bulk operation if error occurs, the execution will stop and Apex code throws an error which can be handled in try catch block.

Database.insert

• Database methods are static methods available in Database class.
• Partial insert is supported.
• Roll back is supported.
• If DML database methods (Database.insert) used, then if error occurs the remaining records will be inserted / updated means partial DML operation will be done.

Example: If you are inserting 10 records.
5 having all the required fields value and remaining 5 records missing required fields value.

In DML statement (insert) all the 10 records will be failed, because if one record is incorrect or error means all other remaining records will not be inserted. It will throw error.

In Database.insert 5 records will be inserted, remaining 5 records will be failed.(i.e. Partial DML Operation).

24. Can you explain the order of execution in Triggers?

Following is the order of execution of events which Salesforce perform before a DML Event.

1. The record is loaded from the database or is initialized in case of upset statement.

2. New record’s field values are overwriting the old values, now depending on the origin of the request this flow varies: if the request is from a UI page then the following validations are performed by Salesforce:

1. Any layout specific rules are checked

2. All the required values are checked at layout and field level

3. All the field formats are validated along with the maximum length of field values

If the request originates other than UI then Salesforce only checks for Validation of foreign keys.

3. Now all the before triggers are executed at the database.

4. Most of the validations are performed again to verify that all the required fields are holding some values and are not null, at this step user defined validations are also executed and the only validation which is not repeated in this step are the rules specific to the layout.

5. After the success of the previous step, the record is reviewed for duplicate records, by running the duplicate rule. If a duplicate is found the flow is stopped and no further actions performed.

6. In this step, record is saved to the database but it not committed yet.

7. Now all the after Triggers are executed.

8. In this step, assignment rules are executed.

9. Now if there is any auto-response rule is present then they are executed.

10. Next in the queues are the workflow, they are executed after the auto response.

11. If the workflow was updating a field, then the fields updated in this step and the flow after this step varies if this was the case.

12. If a field was updated then the before and after update triggers are fired once more and standard validation are also executed again. Custom validation escalation rule and duplicate rules are not required to run again.

13. Once the execution has reached this stage, then process is fired if there are any declared on the object.

14. Now the escalation rules are executed.

15. Entitlement rules are executed if any.

16. If there are any roll-up summary field, then they are calculated at this step and the parent object go through the save process.

17. Now the sharing rules are executed.

18. If we reach this stage, then that means no error has occurred and the data is ready to be committed to the database and is committed now.

Now if there is any post-commit logic like email, then that is executed.

Questions Based on Trigger Context Variables

Hey guys, here i am sharing some questions based on Trigger Context Variables, which are very helpful in interviews.

i) What are the the context variable available with before insert event?

Only Trigger.new is available.

ii) What are the the context variable available with after insert event?

Trigger.new and Trigger.newMap.

iii) What are the the context variable available with before update event?

Trigger.new, Trigger.old, Trigger.newmap and Trigger.oldmap

iv) What are the the context variable available with after update event?

Trigger.new, Trigger.old, Trigger.newmap and Trigger.oldmap

v) What are the the context variable available with before delete event?

Trigger.old and Trigger.oldMap.

vi) What are the the context variable available with after delete event?

Trigger.old and Trigger.oldMap.

vii) What are the the context variable available with after undelete event?

Trigger.new and Trigger.newMap.