Salesforce Trigger Scenarios: Key Interview Questions

In Salesforce development, triggers play a crucial role in automating tasks and ensuring business logic is executed at the right time. This blog will walk you through unique and challenging trigger scenario-based questions designed for Salesforce developers with 3-5 years of experience. Whether you’re preparing for interviews or looking to sharpen your trigger skills, these real-world examples will help you understand how to solve complex problems using Salesforce triggers.

Message to Interviewees

Preparing for a Salesforce interview can be challenging, especially when it comes to understanding how triggers work in real-world scenarios. The key to success is practice! Focus on mastering trigger contexts, bulk processing, and best practices like avoiding recursion and handling related records efficiently. Always test your code in different scenarios to ensure your solution is robust and scalable.

By going through the scenario-based questions in this blog, you’ll be better equipped to tackle complex trigger-related questions in your next interview.


 Interview Series

In this blog series, I have tried to cover all scenario-based Trigger Interview Questions that Salesforce Developers often ask in an interview.

Let's start the interview series on Trigger Scenario Based Questions (Between Interviewer & Candidate).


1. Trigger Order of Execution: Scenario-Based Question

 Interviewer: Imagine you have two triggers on the Account object:


  • Trigger A: It updates a custom field Account.Status__c based on certain criteria.
  • Trigger B: It sends an email notification when the Account.Status__c field is updated.

Both triggers fire on the before update event, and you need to ensure that Trigger A executes before Trigger B. How would you enforce this execution order?

MIND IT!

Concepts Tested:

  • Understanding of trigger execution order.
  • Use of trigger handler classes to control the sequence of execution.

Why this is asked:

This question is designed to evaluate a candidate's knowledge of Salesforce's limitations regarding multiple triggers and how best practices (like using handler classes) can help manage conflicts and ensure smooth execution.


 Interviewee: Salesforce does not guarantee the execution order of triggers when you have multiple triggers on the same object and event. To ensure a specific execution order, you should use a trigger handler pattern where both triggers delegate their logic to a common handler class. This way, you can control the sequence in which the logic is executed.

Real Example:

Let's say you have two triggers on the Account object:

  1. Trigger A (updates Account.Status__c)
  2. Trigger B (sends an email notification when Account.Status__c changes)

To ensure Trigger A executes before Trigger B, both triggers will call a handler class in a specified order.

Step-by-Step Solution:

1. Create a Trigger Handler Class: Define a class that contains the logic for both actions (updating the Status__c field and sending an email).

// apex
public class AccountTriggerHandler {
    
    public static void handleBeforeUpdate(List<Account> oldAccounts, List<Account> newAccounts) {
        // Step 1: Execute Trigger A logic (update Status__c)
        updateAccountStatus(oldAccounts, newAccounts);
        
        // Step 2: Execute Trigger B logic (send email if Status__c changes)
        sendEmailNotification(oldAccounts, newAccounts);
    }
    
    private static void updateAccountStatus(List<Account> oldAccounts, List<Account> newAccounts) {
        for (Account acc : newAccounts) {
            if (/* condition to update Status__c */) {
                acc.Status__c = 'Updated Status';
            }
        }
    }
    
    private static void sendEmailNotification(List<Account> oldAccounts, List<Account> newAccounts) {
        for (Integer i = 0; i < newAccounts.size(); i++) {
            if (oldAccounts[i].Status__c != newAccounts[i].Status__c) {
                // Logic to send email
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                email.setSubject('Account Status Changed');
                email.setToAddresses(new String[] { 'user@example.com' });
                email.setPlainTextBody('The Account Status has been changed.');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
            }
        }
    }
}

2. Modify Both Triggers to Use the Handler Class: Instead of having the logic inside the trigger, both triggers will simply delegate the logic to the handler class.


  • Trigger A:
  • trigger AccountTriggerA on Account (before update) {
        AccountTriggerHandler.handleBeforeUpdate(Trigger.old, Trigger.new);
    }
    

  • Trigger B:
  • trigger AccountTriggerB on Account (before update) {
        AccountTriggerHandler.handleBeforeUpdate(Trigger.old, Trigger.new);
    }
    

Key Points:

  • Single Entry Point: Both triggers now delegate their logic to the AccountTriggerHandler class, which acts as the single entry point for handling all logic.
  • Order of Execution: Inside the handler class, the logic for updating the Status__c field (Trigger A's logic) is executed before sending the email (Trigger B's logic). This ensures that Trigger A's logic always runs before Trigger B's, even though both triggers are on the same object and event.

Benefits of This Approach:

  1. Controlled Execution: You have full control over the execution order.
  2. Maintainability: Centralizing the logic in a handler class makes it easier to maintain and debug.
  3. Best Practices: Using handler classes is a best practice in Salesforce development, especially when dealing with complex trigger logic.

To execute the code in the /* condition to update CustomStatus__c */ section, you need to define a condition that determines when the CustomStatus__c field should be updated. This condition could be based on any logic relevant to your business requirements, such as changes in other fields, specific values, or criteria on the Account object.

Example Condition:

In the example I provided, CustomStatus__c is assumed to be a Text or Picklist field, as these are common data types for status-related fields.

Let’s say you want to update the CustomStatus__c field if the Account Industry changes to Technology.

Here's how you could implement the condition:

//apex
public class AccountTriggerHandler {

    // Method to handle before update logic
    public static void handleBeforeUpdate(List<Account> oldAccounts, List<Account> newAccounts) {
        // Step 1: Execute Trigger A logic (update CustomStatus__c)
        updateAccountStatus(oldAccounts, newAccounts);
        
        // Step 2: Execute Trigger B logic (send email if Industry changes to 'Technology')
        sendEmailNotification(oldAccounts, newAccounts);
    }
    
    // Method to update the CustomStatus__c field based on Industry change
    private static void updateAccountStatus(List<Account> oldAccounts, List<Account> newAccounts) {
        for (Integer i = 0; i < newAccounts.size(); i++) {
            Account oldAcc = oldAccounts[i];
            Account newAcc = newAccounts[i];
            
            // Condition: Update CustomStatus__c if Industry changes to 'Technology'
            if (oldAcc.Industry != newAcc.Industry && newAcc.Industry == 'Technology') {
                newAcc.CustomStatus__c = 'Updated for Tech Industry';
            }
        }
    }
    
    // Method to send email notification when Industry changes to 'Technology'
    private static void sendEmailNotification(List<Account> oldAccounts, List<Account> newAccounts) {
        List<messaging.singleemailmessage> emailsToSend = new List<messaging.singleemailmessage>();
        
        for (Integer i = 0; i < newAccounts.size(); i++) {
            Account oldAcc = oldAccounts[i];
            Account newAcc = newAccounts[i];
            
            // Check if Industry has changed to 'Technology'
            if (oldAcc.Industry != newAcc.Industry && newAcc.Industry == 'Technology') {
                // Create the email message
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                
                // Set the email properties
                email.setSubject('Account Status Updated');
                email.setToAddresses(new String[] { 'user@example.com' }); // Change to actual email address
                email.setPlainTextBody('The Account Industry has been changed to Technology. The status has been updated.');
                
                // Add the email to the list
                emailsToSend.add(email);
            }
        }
        
        // Send all emails at once
        if (!emailsToSend.isEmpty()) {
            Messaging.sendEmail(emailsToSend);
        }
    }
}

Explanation:

  1. handleBeforeUpdate:
    • This method first calls updateAccountStatus() to update the CustomStatus__c field if the Industry changes to 'Technology'.
    • Then it calls sendEmailNotification() to send an email notification if the Industry changes.
  2. updateAccountStatus:
    • This method checks if the Industry field has changed from the old value to 'Technology'. If so, it updates the CustomStatus__c field.
  3. sendEmailNotification:
    • This method sends an email if the Industry changes to 'Technology'. It creates a list of email messages and sends them at once using Messaging.sendEmail().
    • The email subject and body can be customized as needed. In this example, it's a simple notification that the Account Industry was changed.

Trigger Code:

trigger AccountTriggerA on Account (before update) {
    AccountTriggerHandler.handleBeforeUpdate(Trigger.old, Trigger.new);
}

How it Works:

  • Account Update: When you update an Account and change the Industry field to Technology, the trigger will fire.
  • CustomStatus__c Update: If the Industry changes to Technology, the CustomStatus__c field will be updated.
  • Email Notification: An email will be sent to the specified address notifying that the Industry has been updated.

You can modify the email content and recipient email addresses as needed for your specific use case.


Share This Post:

About The Author

Hey, my name is Saurabh Samir and I am a Salesforce Developer. I have been helping to elevate your Lightning Web Components (LWC) Knowledge. Do comment below if you have any questions or feedback.