Scenario:
Write a trigger on the Task object to update the Rating field of the related Account when a Task is completed:
1️⃣ If the Task Priority is High → Rating = Hot
2️⃣ If the Task Priority is Normal → Rating = Warm
3️⃣ If the Task Priority is Low → Rating = Cold
Here’s the simple solution:
trigger TaskTrigger on Task (after insert, after update) {
Map accountPriorityMap = new Map();
for (Task t : Trigger.new) {
if (t.Status == 'Completed' && t.WhatId != null && t.WhatId.getSObjectType() == Account.sObjectType) {
accountPriorityMap.put(t.WhatId, t.Priority);
}
}
List<Account> accountsToUpdate = [SELECT Id, Rating FROM Account WHERE Id IN :accountPriorityMap.keySet()];
for (Account acc : accountsToUpdate) {
String priority = accountPriorityMap.get(acc.Id);
acc.Rating = priority == 'High' ? 'Hot' :
priority == 'Normal' ? 'Warm' :
priority == 'Low' ? 'Cold' : acc.Rating;
}
if (!accountsToUpdate.isEmpty()) {
update accountsToUpdate;
}
}
Key Points:
✅ Trigger runs after Task is created or updated.
✅ Updates the Account’s Rating based on Task Priority.
✅ Bulkified to handle multiple Tasks efficiently.
💡 Keep practicing scenarios like this to ace Salesforce interviews! DM me for test classes or any questions.
#Salesforce #TriggerScenarios #SalesforceInterview #TrailblazerCommunity #LearnSalesforce