Introduction:
Salesforce triggers are powerful mechanisms used to automate business processes and perform specific actions when certain events occur within the Salesforce platform. In a scenario-based interview, candidates may be asked to demonstrate their understanding of triggers by solving real-world problems and writing code to implement the desired functionality. In this blog post, we will explore a few scenario-based interview questions related to triggers in Salesforce, along with example code solutions.
Scenario 1: Creating a Before Trigger
Question:
Imagine you are tasked with implementing a trigger that automatically sets the "Closed Date" field to the current date and time whenever a Case record's status is changed to "Closed." Write a before trigger in Apex to accomplish this.
Solution:
trigger CaseClosedDateTrigger on Case (before update) {
for (Case caseRecord : Trigger.new) {
if (caseRecord.Status == 'Closed') {
caseRecord.ClosedDate = DateTime.now();
}
}
}
Explanation:
In this scenario, we create a before update trigger on the Case object. The trigger iterates over the list of Case records being updated (Trigger.new) and checks if the status of each record is set to "Closed." If the condition is met, the trigger sets the "ClosedDate" field of the Case record to the current date and time using the `DateTime.now()` method.
Scenario 2: Handling Trigger Recursion
Question:
Suppose you need to prevent trigger recursion when updating the "Account" object. Specifically, you want to avoid an infinite loop where a trigger update on an Account record causes subsequent trigger updates. Write an after update trigger that achieves this recursion prevention.
Solution:
trigger AccountRecursionTrigger on Account (after update) {
Set<Id> processedAccountIds = new Set<Id>();
for (Account accountRecord : Trigger.new) {
if (!processedAccountIds.contains(accountRecord.Id)) {
// Add current Account record Id to the set
processedAccountIds.add(accountRecord.Id);
// Perform necessary actions
// ...
}
}
}
Explanation:
To prevent trigger recursion, we can utilize a set (`processedAccountIds`) to keep track of the Account record Ids that have already been processed. The trigger iterates over the updated Account records (Trigger.new) and checks if the current record's Id is present in the set. If the Id is not found, it indicates that the record hasn't been processed before, so we add it to the set and proceed with the necessary actions.
Scenario 3: Bulkifying Trigger Logic
Question:
You have been given the task of writing a trigger on the "Opportunity" object to calculate and update the average amount of all related Opportunities on the associated Account record. Ensure that your trigger logic can handle bulk updates efficiently. Write the trigger code to accomplish this.
Solution:
trigger UpdateAccountAvgAmountTrigger on Opportunity (after insert, after update, after delete, after undelete) {
Set<Id> accountIds = new Set<Id>();
if (Trigger.isInsert || Trigger.isUndelete) {
for (Opportunity oppRecord : Trigger.new) {
accountIds.add(oppRecord.AccountId);
}
} else if (Trigger.isUpdate || Trigger.isDelete) {
for (Opportunity oppRecord : Trigger.old) {
accountIds.add(oppRecord.AccountId);
}
}
List<Account> accountsToUpdate = new List<Account>();
for (AggregateResult result : [SELECT AccountId, AVG(Amount) avgAmount
FROM Opportunity
WHERE AccountId IN :accountIds
GROUP BY AccountId])
{
Account account = new Account(
Id = (Id)result.get('AccountId'),
Avg_Opportunity_Amount__c = (Decimal)result.get('avgAmount')
);
accountsToUpdate.add(account);
}
update accountsToUpdate;
}
Explanation:
In this scenario, we create an after trigger on the Opportunity object that calculates and updates the average amount of all related Opportunities on the associated Account record. The trigger logic efficiently handles bulk updates by collecting the AccountIds affected by the trigger operation. Then, using an aggregate query, we calculate the average amount for each Account and update the corresponding Account records in bulk.
Conclusion:
Scenario-based interview questions provide a valuable opportunity for Salesforce developers to showcase their understanding of triggers and their ability to solve real-world problems using Apex code. By practicing and familiarizing yourself with such scenarios, you can enhance your skills and increase your chances of success in Salesforce trigger-related interviews. Remember to analyze the requirements carefully, design efficient code solutions, and demonstrate a solid understanding of trigger best practices. Good luck!