Skip to main content
Ilya Potapov (Krapka) ha fatto una domanda in #Apex
Hello. For now I have some Accounts with linked Tasks to each of them. When working with particular Account is there any way to get the number of linked Tasks to this Account? Or the right way is to query throw

Tasks and count related Tasks to each of Account? Thanks.
2 risposte
  1. 4 feb 2022, 16:12
    Hi Ilya,

    Try with below code.

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

    }

    }

    If this helps, please mark it as best answer.

    Thanks!!
0/9000