Apex Triggers - 16 (TCS Interview Question)
1. Scenario Overview
This automation addresses a TCS Interview Question involving roll-up style calculation across parent-child relationships. The Account object contains a custom text field named
Max_OPP__c. The requirement mandates that this field must always display the Name of the related Opportunity record that has the highest Amount.Because this value can change across any data mutation phase, the trigger handles a full suite of events (
after insert, after update, after delete, and after undelete) to safely re-calculate metrics on parent Accounts.or
Update the Parent Account field with the Opportunity Name that has the Highest Amount.
2. Apex Handler Class
java
public class OpportunityTriggerHandler {
public static void updateMaxOpportunityName(List<Opportunity> newOpps, Map<Id, Opportunity> oldOppMap) {
Set<Id> accountIds = new Set<Id>();
// Phase 1: Track all impacted Account IDs across record lifecycles
if (newOpps != null) {
for (Opportunity opp : newOpps) {
if (opp.AccountId != null) {
accountIds.add(opp.AccountId);
}
// Handle re-parenting changes: track the previous parent account
if (oldOppMap != null && oldOppMap.containsKey(opp.Id)) {
Opportunity oldOpp = oldOppMap.get(opp.Id);
if (oldOpp.AccountId != null && oldOpp.AccountId != opp.AccountId) {
accountIds.add(oldOpp.AccountId);
}
}
}
}
if (accountIds.isEmpty()) {
return;
}
// Phase 2: Query accounts with their highest related opportunity via ordered subqueries
List<Account> accountsToUpdate = new List<Account>();
for (Account acc : [SELECT Id, Max_OPP__c,
(SELECT Name, Amount FROM Opportunities WHERE Amount != null ORDER BY Amount DESC LIMIT 1)
FROM Account WHERE Id IN :accountIds]) {
if (!acc.Opportunities.isEmpty()) {
// Assign the name of the opportunity that holds the maximum amount value
acc.Max_OPP__c = acc.Opportunities[0].Name;
} else {
// Clear out the field value if no opportunities remain
acc.Max_OPP__c = '';
}
accountsToUpdate.add(acc);
}
// Phase 3: Bulk DML engine call
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
}
Use code with caution.
3. Apex Trigger
java
trigger OpportunityTrigger on Opportunity (after insert, after update, after delete, after undelete) {
// route records safely to the handler class based on active DML execution channels
if (Trigger.isAfter) {
if (Trigger.isInsert || Trigger.isUndelete) {
OpportunityTriggerHandler.updateMaxOpportunityName(Trigger.new, null);
} else if (Trigger.isUpdate) {
OpportunityTriggerHandler.updateMaxOpportunityName(Trigger.new, Trigger.oldMap);
} else if (Trigger.isDelete) {
OpportunityTriggerHandler.updateMaxOpportunityName(Trigger.old, null);
}
}
}
Comments
Post a Comment