Last active
November 20, 2022 18:44
-
-
Save danielfreitasce/0db7d005f4df3a7fdab973e1770e4a7d to your computer and use it in GitHub Desktop.
Update the number of open tasks in a SObject | Exemple class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class UpdateNoOfOpenTask { | |
public static void updateNoOfTasks(List<Task> newTasks) { | |
//WhoId holds the Lead or Contact Id | |
Set<Id> contactIds = new Set<Id>(); | |
for(Task t : newTasks) { | |
if(t.WhoId != null && String.valueOf(t.WhoId).startsWith('003')) { | |
contactIds.add(t.WhoId); | |
} | |
} | |
Map<Id, Contact> contactMap = new Map<Id, Contact>([SELECT Id, No_of_Open_Tasks__c FROM Contact WHERE Id IN :contactIds]); | |
for(Task t : newTasks) { | |
if(contactMap.containsKey(t.WhoId)) { | |
contactMap.get(t.WhoId).No_of_Open_Tasks__c += 1; | |
} | |
} | |
update contactMap.values(); | |
} | |
public static void updateNoOfTasks(List<Task> newTasks, Map<Id, Task> oldMap) { | |
Set<Id> contactIds = new Set<Id>(); | |
for(Task t : newTasks) { | |
if(t.IsClosed && !oldMap.get(t.Id).IsClosed && t.WhoId != null && String.valueOf(t.WhoId).startsWith('003')) { | |
contactIds.add(t.WhoId); | |
} | |
} | |
Map<Id, Contact> contactMap = new Map<Id, Contact>([SELECT Id, No_of_Open_Tasks__c FROM Contact WHERE Id IN :contactIds]); | |
for(Contact con : contactMap.values()) { | |
con.No_of_Open_Tasks__c = 0; | |
} | |
for(AggregateResult ar : [SELECT WhoId, COUNT(Id) total | |
FROM Task | |
WHERE IsClosed = false AND WhoId in :contactIds | |
GROUP BY WhoId]) | |
{ | |
String who = String.valueOf(ar.get('WhoId')); | |
Decimal total = (Decimal) (ar.get('total')); | |
contactMap.get(who).No_of_Open_Tasks__c = total; | |
} | |
update contactMap.values(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment