Trigger: Delete all Upcoming Task from Account

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;
}

Leave a Reply