Salesforce Interview Questions on Triggers

Salesforce Interview Questions on Triggers

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

What is a Trigger?

Apex triggers enable you to perform custom actions before or after events to records in Salesforce, such as insertions, updates, or deletions. Just like database systems support triggers, Apex provides trigger support for managing records.

Use triggers to perform tasks that can’t be done by using the point-and-click tools in the Salesforce user interface. For example, if validating a field value or updating a field on a record, use validation rules and workflow rules instead.

What is Trigger Syntax?

trigger TriggerName on ObjectName (trigger_events) {
   code_block
}

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

What are different type of Triggers?

There are two types of triggers:

  • Before triggers are used to perform a task before a record is inserted or updated or deleted. These are used to update or validate record values before they are saved to the database.
  • After triggers are used if we want to use the information set by Salesforce system and to make changes in the other records. are used to access field values that are set by the system (such as a record’s Id or LastModifiedDate field), and to affect changes in other records. The records that fire the after trigger are read-only.

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.

Read the Apex Developer Guide for more detailed considerations.

What are context variables in triggers?

All triggers define implicit variables that allow developers to access run-time context. These variables are contained in the System.Trigger class.

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

  • isExecuting: Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or an executeanonymous() API call.
  • 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 (that is, 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 in before triggers.
  • newMap: A 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.
  • old : Returns a list of the old versions of the sObject records. This sObject list is only available in update and delete triggers.
  • oldMap: A map of IDs to the old versions of the sObject records. This map is only available in update and delete triggers.
  • size: The total number of records in a trigger invocation, both old and new.

Refer to Trigger context variables in salesforce link for more details.

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. NewMap is only available in after insert, before and after the update and after undelete.

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

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.

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.

Define Recursive Trigger and how to avoid it?

There is a possibility that the result of the trigger can end up calling the same trigger again and can run in a loop, this is known as a recursive trigger. To avoid this scenario we should create a static variable and check the value of this variable before we execute anything in the trigger. For more details refer to below link:

Avoid recursive trigger in salesforce

What do you mean by the bulkifying trigger?

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.

Bulk Apex Trigger trailhead

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.

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.

  1. Now all the before triggers are executed at the database.
  2. 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.
  3. 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.
  4. In this step, record is saved to the database but it not committed yet.
  5. Now all the after Triggers are executed.
  6. In this step, assignment rules are executed.
  7. Now if there is any auto-response rule is present then they are executed.
  8. Next in the queues are the workflow, they are executed after the auto response.
  9. 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.
  10. 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.
  11. Once the execution has reached this stage, then process is fired if there are any declared on the object.
  12. Now the escalation rules are executed.
  13. Entitlement rules are executed if any.
  14. If there are any roll-up summary field, then they are calculated at this step and the parent object go through the save process.
  15. Now the sharing rules are executed.
  16. 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.
  17. Now if there is any post-commit logic like email, then that is executed.

 

For more details about trigger please refer below links

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm

Trailhead get started with Triggers

Other posts related to interview questions

Salesforce lightning interview questions

I will keep adding more questions to Salesforce Interview Questions on Triggers.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/salesforce-interview-questions-on-triggers/

4 comments

Skip to comment form

    • naveen on December 24, 2019 at 8:42 pm
    • Reply

    What are the problems you have encountered when calling batch apex from the trigger.

    • amit on April 29, 2020 at 1:26 pm
    • Reply

    Create a junction object named ‘Job Application’ between two objects named ‘Position’ and ‘Candidate’.The position and candidate has many to many relationships which will be established due to the junction object. Create a status field of type picklist on both position and candidate. If the status on a candidate record is updated to ‘Approved’, the status field on position should be updated to ‘Approved’ only if status on all related candidates have been updated to ‘Approved’.

    • Harsha on May 26, 2020 at 3:19 am
    • Reply

    Thank you Ankush Dureja for sharing inputs.

    Hello Naveen,

    As we are aware we can call Batch Apex from Trigger. Point is, there are potential limits for usage of BatchApex from triggers, you can have only 5 Batch called or executing crossing this count means you exhausted limit and no more can be called.

    Just sharing you one more point, you can also batch apex from APex class using if(System.IsBatch()) and runs your Batch Apex. You might be aware but thought of sharing it. Thank you,

    Harsha

      • Manu on September 4, 2021 at 9:35 pm
      • Reply

      What if we need to proceed after 5 batches ? What’s the solution please share

Leave a Reply

Your email address will not be published.