function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Josh HarshJosh Harsh 

Activity Count Trigger Help

Hello,

I currently have a trigger to count the number of tasks related to an Account. The trigger works for the most part, it does not work when an Account is merged with another Account. Can someone assist in helping me find why the code is not recounting the activity upon the change of the What.ID on the task?

Below is the code.


trigger SumTasksTrigger on Task (after insert, after update, after delete) {

    set<Id> set_id = new set<Id>();
    
    List<Account> acc_list = new List<Account>();
    
    if(Trigger.isInsert || Trigger.isUpdate){
        for(Task T: Trigger.new){
            set_id.add(T.WhatId);
            
        }
        
    }
    
    else if(Trigger.isDelete){
        for(Task T: Trigger.old){
            set_id.add(T.WhatId);
            
        }
        
    }
    
    if(Trigger.isAfter &&(Trigger.isInsert || trigger.isUpdate ||  Trigger.isDelete)){
        acc_list = [SELECT Id, Number_of_Tasks__c,(SELECT Id FROM Tasks WHERE Status = 'Completed' AND (CS_Activity__c = FALSE)) FROM Account WHERE Id IN: set_id];
        
        for(Account acc: acc_list){
            if(acc_list.size()>0)
                acc.Number_of_Tasks__c = acc.Tasks.size();
            else
                acc.Number_of_Tasks__c = 0;
        
    }
    
    if(!acc_list.isEmpty())
        update acc_list;

}

}
CRMScienceKirkCRMScienceKirk
I could be wrong, but I don't think updates to child records of either merged parent will fire their respective triggers.

Link:  https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_merge_statements.htm

Makes it sounds like you'll want to have an after delete trigger on the Account record where you'll be comparing the Account.MasterRecordId field of the new vs old records to identify recently merged records.  If you spot a difference, add the new MasterRecordId to a set of Ids and pass it to a new method that determines the new Task counts for each winning Account Id passed to it.  Then revise your Task trigger accordingly.