Hi Ilya, Try with below code.
If this helps, please mark it as best answer.Thanks!!trigger CountTasks on Account (before insert, before update) {
// Put all Account into a Set
Set<id> allAccIds = new Set<id>();
for (Account acc : Trigger.new) {
allAccIds.add(acc.ID);
System.debug('ID added: ' + acc.ID);
}
//Query All Tasks to find Tasks with matching IDs
List allTasks = [SELECT Id, Status, WhatID from Task
WHERE WhatID IN :allAccIds];
System.debug('allTasks is ' + allTasks.size());
List TaskArray = new List(); //All Tasks
Map elCountAll = new Map(); //Count of All Tasks
for (Task u : allTasks) {
TaskArray.add(u.WhatID);
}
System.debug(allTasks.size());
// Get the matching tasks from the Map - and count Status
//Start with our Account
for (Account acc : Trigger.new) {
//Count all Tasks
for(String key : TaskArray)
{
if(!elCountAll.containsKey(key)){
elCountAll.put(key,0);
}
Integer currentInt=elCountAll.get(key)+1;
elCountAll.put(key,currentInt);
}
acc.countofAllTasks__c = elCountAll.get(acc.ID);
}
}
2 Antworten