Salesforce Apex Trigger Scenario based Interview Questions

Ready to nail your Salesforce Apex Trigger interview? Let’s dive into Apex Trigger scenario-based interview questions to boost your skills and ace that interview. Here’s how to handle common scenarios effectively during your prep.

Business Use Case: 

In a customer support environment, efficient communication and follow-up are crucial for resolving cases promptly. However, sometimes cases are created without a designated primary contact associated with the account. In such scenarios, it’s important to ensure that follow-up actions are still taken to address the issue effectively.

Functional Requirements:

  1. Primary Contact Assignment: Identify cases without a primary contact and assign the most recent primary contact from the associated account.
  2. Event Creation: Automatically create follow-up events for these cases, scheduled for a specified timeframe from the current date.

Code

Trigger

trigger caseTrg on Case (before insert)
{
if(trigger.isBefore && trigger.isInsert)
{
CaseTriggerHandler.trgMethod(trigger.new);
}
}

Handler Class

public class CaseTriggerHandler
{
    public static void trgMethod(List<Case> newCaseList)
    {
        Set<Id> parentAccountIds = new Set<Id>();
        for(Case newCase : newCaseList)
        {
            if(newCase.AccountId != null && newCase.ContactId == null)
            {
                parentAccountIds.add(newCase.AccountId);
            }
        }
        if(parentAccountIds.isEmpty())
        {
            return;
        }

        // Most recent primary contact PER account (no LIMIT 1: that would return
        // a single contact for the whole batch and break bulk inserts)
        Map<Id,Contact> conMap = new Map<Id,Contact>();
        for(Contact con : [SELECT Id, AccountId FROM Contact
                           WHERE AccountId IN :parentAccountIds AND Primary_Contact__c = true
                           ORDER BY LastModifiedDate DESC])
        {
            if(!conMap.containsKey(con.AccountId))
            {
                conMap.put(con.AccountId, con); // first row = most recently modified
            }
        }

        List<Event> eventList = new List<Event>();
        for(Case csRcd : newCaseList)
        {
            if(csRcd.AccountId == null || csRcd.ContactId != null)
            {
                continue; // nothing to assign
            }
            Contact conRcd = conMap.get(csRcd.AccountId);
            if(conRcd == null)
            {
                csRcd.addError('There is no primary contact present on selected account');
                continue;
            }
            csRcd.ContactId = conRcd.Id;

            Datetime startDateTime = Datetime.now().addDays(3);
            eventList.add(new Event(
                Subject = csRcd.Subject,
                WhoId = conRcd.Id,
                StartDateTime = startDateTime,
                EndDateTime = startDateTime.addHours(3)
            ));
        }
        if(!eventList.isEmpty())
        {
            insert eventList;
        }
    }
}

 width=
Business Use Case: 

In a sales organization, managing relationships between opportunities and contacts is vital for successful deal closure. The Opportunity Contact Role object in Salesforce allows linking contacts to opportunities and specifying their roles in the sales process. Ensuring accurate and efficient management of these roles is crucial for effective sales operations.

Functional Requirements:

  1. Preventing Role Assignment on Closed Opportunities: Users should not be allowed to assign contact roles to opportunities that are already closed, as it’s unnecessary and could lead to data inconsistency.
  2. Avoiding Duplicate Contact Roles: Duplicate contact roles on the same opportunity should be prevented to maintain data integrity and avoid confusion.

Code

Trigger

trigger ocrTrigger on OpportunityContactRole (before insert)
{
if(trigger.isBefore && trigger.isInsert)
{
OppConRoleHandler.trgMethod(trigger.new);
}
}

Handler Class

public class OppConRoleHandler
{
public static void trgMethod(List<OpportunityContactRole> newRecordList)
{
Set<Id> oppIds = new Set<Id>();
Set<Id> conIds = new Set<Id>();
Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>();
Map<String,OpportunityContactRole> existingRolesMap = new Map<String,OpportunityContactRole>();

if(!newRecordList.isEmpty())
{
for(OpportunityContactRole ocr : newRecordList)
{
if(ocr.OpportunityId != null)
{
oppIds.add(ocr.OpportunityId);
}
if(ocr.ContactId != null)
{
conIds.add(ocr.ContactId);
}
}
}

for(Opportunity opp : [Select Id,IsClosed from Opportunity where Id IN : oppIds])
{
oppMap.put(opp.Id,opp);
}

for(OpportunityContactRole existingRole : [Select Id,ContactId,OpportunityId from OpportunityContactRole
where ContactId IN : conIds and OpportunityId IN : oppIds])
{
existingRolesMap.put(existingRole.OpportunityId+'-'+existingRole.ContactId,existingRole);
}

for(OpportunityContactRole ocrRecord : newRecordList)
{
Opportunity opp = oppMap.get(ocrRecord.OpportunityId);

if(opp.IsClosed)
{
ocrRecord.addError('Cannot create Opportunity Contact Role on a closed Opportunity');
}
String key = ocrRecord.OpportunityId+'-'+ocrRecord.ContactId;

if(existingRolesMap.containsKey(key))
{
ocrRecord.addError('Contact role already exists on the opportunity');
}
}
}
}

Trigger Scenario Based Questions in Salesforce

Business Use Case: 

A company uses Salesforce to manage their sales processes. They have a requirement to automatically update contact roles on opportunities when the type of opportunity changes. This is to ensure that the appropriate contacts are associated based on the type of opportunity.

Code

Trigger

trigger oppTrg on Opportunity (after update)
{
if(trigger.isAfter && trigger.isUpdate)
{
OpportunityTriggerHandler.trgMethod(trigger.new,trigger.oldMap);
}
}

Handler Class

public class OpportunityTriggerHandler
{
    public static void trgMethod(List<Opportunity> newList, Map<Id,Opportunity> oldMap)
    {
        // 1. Only Opportunities whose Type actually changed
        List<Opportunity> changedOpps = new List<Opportunity>();
        Set<Id> parentAccIds = new Set<Id>();
        for(Opportunity newOpp : newList)
        {
            Opportunity oldOpp = oldMap.get(newOpp.Id);
            if(newOpp.AccountId != null && oldOpp.Type != newOpp.Type)
            {
                changedOpps.add(newOpp);
                parentAccIds.add(newOpp.AccountId);
            }
        }
        if(changedOpps.isEmpty())
        {
            return;
        }

        // 2. Key = AccountId + Type, so a contact is only matched within its OWN account
        Map<String,Contact> conTypeMap = new Map<String,Contact>();
        for(Contact relatedCon : [SELECT Id, Type__c, AccountId FROM Contact
                                  WHERE AccountId IN :parentAccIds AND Type__c != null])
        {
            conTypeMap.put(relatedCon.AccountId + '|' + relatedCon.Type__c, relatedCon);
        }

        List<OpportunityContactRole> ocrList = new List<OpportunityContactRole>();
        Set<Id> oppIdsToReset = new Set<Id>();
        for(Opportunity opp : changedOpps)
        {
            Contact conRcd = conTypeMap.get(opp.AccountId + '|' + opp.Type);
            if(conRcd == null)
            {
                opp.addError('No contact found with the type ' + opp.Type + ' on this account');
                continue;
            }
            oppIdsToReset.add(opp.Id);
            ocrList.add(new OpportunityContactRole(OpportunityId = opp.Id, ContactId = conRcd.Id));
        }

        // 3. Replace the old contact roles only for the Opportunities we re-assigned
        if(!ocrList.isEmpty())
        {
            delete [SELECT Id FROM OpportunityContactRole WHERE OpportunityId IN :oppIdsToReset];
            insert ocrList;
        }
    }
}

Business Use Case: 

Your company is seeking to optimize its customer support processes by implementing an automated escalation system for critical cases. Currently, there is a need to swiftly identify cases requiring escalation and ensure timely follow-up actions. Your team has been tasked with developing a solution that triggers the creation of follow-up tasks for primary contacts associated with escalated cases. This solution aims to streamline communication and resolution processes, ultimately improving customer satisfaction and service efficiency

Code

Trigger

trigger caseTrg on Case (after update)
{
if(trigger.isAfter && trigger.isUpdate)
{
CaseTriggerHandler.trgMethod(trigger.new,trigger.oldMap);
}
}

Handler Class

public class CaseTriggerHandler
{
    public static void trgMethod(List<Case> newCaseList, Map<Id,Case> oldCaseMap)
    {
        // 1. Cases that just became "Escalation Required"
        List<Case> escalatedCases = new List<Case>();
        Set<Id> parentAccIds = new Set<Id>();
        for(Case newCase : newCaseList)
        {
            Case oldCase = oldCaseMap.get(newCase.Id);
            if(newCase.AccountId != null && newCase.Escalation_Required__c
               && !oldCase.Escalation_Required__c)
            {
                escalatedCases.add(newCase);
                parentAccIds.add(newCase.AccountId);
            }
        }
        if(escalatedCases.isEmpty())
        {
            return;
        }

        // 2. Most recent primary contact PER account (not LIMIT 1 for the whole batch)
        Map<Id,Contact> primaryConMap = new Map<Id,Contact>();
        for(Contact con : [SELECT Id, AccountId FROM Contact
                           WHERE AccountId IN :parentAccIds AND Primary_Contact__c = true
                           ORDER BY LastModifiedDate DESC])
        {
            if(!primaryConMap.containsKey(con.AccountId))
            {
                primaryConMap.put(con.AccountId, con);
            }
        }

        // 3. One follow-up Task per escalated Case, linked to both the Contact and the Case
        List<Task> taskList = new List<Task>();
        for(Case cs : escalatedCases)
        {
            Contact primaryCon = primaryConMap.get(cs.AccountId);
            if(primaryCon == null)
            {
                continue;
            }
            taskList.add(new Task(
                Subject = 'Follow up task',
                WhoId = primaryCon.Id,
                WhatId = cs.Id,
                Status = 'Not Started',
                Priority = 'High',
                Description = 'Follow-up for escalated case ' + cs.CaseNumber
            ));
        }
        if(!taskList.isEmpty())
        {
            insert taskList;
        }
    }
}

 

Business Use Case: 

Our company aims to enhance account management within our Salesforce instance. We require a solution that automatically updates a custom field, “Max_Opportunity_Amount__c,” on the Account object whenever related Opportunities are modified. This update should reflect the maximum Opportunity amount associated with each Account. Additionally, the update should occur whenever an Opportunity is inserted, updated, deleted, undeleted, or closed. This functionality aims to provide our sales team with real-time insights into the most significant opportunities within each account, thereby optimizing their strategic decision-making and fostering stronger client relationships.

Code

Trigger

trigger oppTrg on Opportunity (after insert,after Delete,after Update,after Undelete)
{
if(trigger.isAfter && (trigger.isInsert || trigger.isUndelete))
{
OpportunityTriggerHandler.trgMethod(trigger.new,null);
}
else if(trigger.isAfter && trigger.isUpdate)
{
OpportunityTriggerHandler.trgMethod(trigger.new,trigger.oldMap);
}
else if(trigger.isAfter && trigger.isDelete)
{
OpportunityTriggerHandler.trgMethod(trigger.old,null);
}
}

Handler Class

public class OpportunityTriggerHandler
{
    public static void trgMethod(List<Opportunity> newOppList, Map<Id,Opportunity> oldOppMap)
    {
        // 1. Collect every Account affected (old and new parent when AccountId changes)
        Set<Id> accIds = new Set<Id>();
        for(Opportunity newOpp : newOppList)
        {
            if(newOpp.AccountId != null)
            {
                accIds.add(newOpp.AccountId);
            }
            if(oldOppMap != null)
            {
                Opportunity oldOpp = oldOppMap.get(newOpp.Id);
                if(oldOpp.AccountId != null)
                {
                    accIds.add(oldOpp.AccountId);
                }
            }
        }
        if(accIds.isEmpty())
        {
            return;
        }

        // 2. Let the database work out the max per Account (one aggregate query)
        Map<Id,Decimal> maxOppMap = new Map<Id,Decimal>();
        for(AggregateResult ar : [SELECT AccountId accId, MAX(Amount) maxAmount
                                  FROM Opportunity
                                  WHERE AccountId IN :accIds
                                  GROUP BY AccountId])
        {
            maxOppMap.put((Id) ar.get('accId'), (Decimal) ar.get('maxAmount'));
        }

        // 3. Accounts with no Opportunities left get 0
        List<Account> listToUpdateAcc = new List<Account>();
        for(Id accId : accIds)
        {
            Decimal maxAmount = maxOppMap.get(accId);
            listToUpdateAcc.add(new Account(
                Id = accId,
                Max_Opportunity_Amount__c = maxAmount == null ? 0 : maxAmount
            ));
        }
        update listToUpdateAcc;
    }
}

Note: an earlier version kept a single running maximum shared by all Accounts and only looked at closed Opportunities, so bulk updates gave wrong values. An aggregate MAX(Amount) … GROUP BY AccountId query avoids both problems.

With these scenario-based interview questions in your arsenal, you’re set to shine in your Salesforce Apex Trigger interview. Keep practicing, stay confident, and showcase your problem-solving skills. You’ve got this!

Checkout more scenarios –

30 Salesforce Apex Trigger Examples – Part 1

Want to learn Salesforce Development? Explore our courses or contact our team.

Share Now

Learn Salesforce Flows 👇 Beginner-friendly course | More than 90+ tutorials

Prepare for PD1 Exam 3 Mock Practice Sets to prepare for the exam

Book a 1:1 Call 👇 Doubt related to Salesforce Flow?

Categories

What’s Trending