Example: Write a trigger logic such as if Account Rating change from Hot to any then delete all upcoming Task associated with that Account.
Solution
Set<Id> setId = new Set<Id>();
for (Id acc : trigger.newMap.keySet()) {
if (Trigger.oldMap.get(acc).Rating == 'Hot' && Trigger.newMap.get(acc).Rating != 'Hot') {
setId.add(acc);
}
}
if(!setId.isEmpty()) {
Date todaysDate = System.today();
List<Task> tasksToDelete = [SELECT Id From Task WHERE ActivityDate >:todaysDate and WhatId IN:setId];
delete tasksToDelete;
}
Scenario
When an Account Rating changes from Hot to anything else, the follow-up Tasks planned for the future are usually no longer needed. This logic deletes them automatically.
How the code works
It loops through Trigger.newMap.keySet() and compares the old and new Rating of each Account using Trigger.oldMap.
Accounts whose Rating was Hot and is no longer Hot are collected in a Set of Ids.
If the Set is not empty, one query finds the Tasks whose WhatId is one of those Accounts and whose ActivityDate is later than today.
All matching Tasks are deleted with a single delete statement.
Where to place this code
Use it inside an update trigger on Account, usually after update. Trigger.oldMap is only available in update and delete contexts.
Points to note
Only Tasks with a due date after today are deleted. Tasks due today, overdue, or with no due date are kept.
Completed Tasks with a future date are also deleted. Add AND IsClosed = false to the query if you want to delete only open Tasks.
Deleted records go to the Recycle Bin, but test in a sandbox first.
How to test
Create an Account with Rating Hot and add a Task due next week.
Change the Rating to Warm and save.
Check the Account activity list. The upcoming Task should be gone.
FAQ
Why use a Set? A Set avoids duplicates and works directly with the IN operator.
Why check that the Set is not empty? It avoids running a query and a delete when no Account matched.