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
SFDC@ErrorSFDC@Error 

Count TAsk on Case

Hi All
How can i count total number of task related to case.I have written class and trigger, but its not calculating properly. Initially i am creating 20 tasks at time but its counting as 1.
public with sharing class taskCountUtility {
    public static Boolean didRun = false;
    
    public static void updateLeadTaskCounts(Set<ID> leadIds) {
 
        if (didRun == false) { 
            didRun = true;
 
            List<Case > lead = [SELECT ID, Activities_Count__c  , (SELECT ID FROM Tasks),(select id from Emails) FROM Case  WHERE ID IN :leadIds];
            List<Case > updateLead = new List<Case>();
system.debug('lead '+lead);
            for (Case l : lead) {
                
                Integer count = l.tasks.size();
 system.debug('count '+count);
                if (l.Activities_Count__c  != count) {
                    l.Activities_Count__c = count;
                    updateLead.add(l);
                }
            }
            
            try {
                update updateLead;
            } catch (Exception e) {
               
            }
        }
    }
}
 
trigger updateCaseTaskCount on Task (after insert,after delete,after update,after undelete) {
 
    Set<ID> leadIds = new Set<ID>();
    String prefix =  '500';
 
    if (Trigger.new != null) {
        for (Task t : Trigger.new) {
           if (t.WhatId != null && String.valueOf(t.whatId).startsWith(prefix) ) {
                leadIds.add(t.whatId);
            }
        }
    }
 
    if (Trigger.old != null) {
        for (Task t : Trigger.old) {
            if (t.WhatId != null && String.valueOf(t.whatId).startsWith(prefix) ) {
                leadIds.add(t.whatId);
            }
        }
    }
 
    if (leadIds.size() > 0)
        taskCountUtility.updateLeadTaskCounts(leadIds);
 
 
}

 
Andrew GAndrew G
I ran an eye over your code and it looks OK.
I then copied it to my test environment and created a test class with 3 x methods.  The classes passed both insert and update of 20 records.
Test class included for clarity.  
So how exactly are you seeing the error?  Is there a bulk upload or other trigger which inserts the new tasks?

Regards
Andrew
@isTest
private class taskCountUtility_Test {
	
	@isTest static void test_method_one() {
		// Implement test code

		List<Account> testAccounts = TestClassHelper.createStandardAccs(1);
		Insert testAccounts;

		List<Case> testCases = TestClassHelper.createCases(1, 'low', testAccounts[0].Id);
		Insert testCases;

		List<Task> testTasks = TestClassHelper.createTasks(20, testCases[0].Id);
		Insert testTasks;

		List<Task> insTasks = new List<Task>();
		insTasks = [SELECT Id FROM Task WHERE WhatId = :testCases[0].Id];

		System.assertEquals(insTasks.size(),20);

	}
	
	@isTest static void test_method_two() {
		// Implement test code
		List<Account> testAccounts = TestClassHelper.createStandardAccs(1);
		Insert testAccounts;

		List<Case> testCases = TestClassHelper.createCases(1, 'low', testAccounts[0].Id);
		Insert testCases;

		List<Task> testTasks = TestClassHelper.createTasks(20, testCases[0].Id);
		Insert testTasks;

		List<Task> insTasks = new List<Task>();
		insTasks = [SELECT Id FROM Task WHERE WhatId = :testCases[0].Id];
		List<Task> updateTasks = new List<Task>();
		for (Task task : insTasks ) {
			task.Priority = 'Low';
			updateTasks.add(task);
		}
		Update updateTasks;

		insTasks = [SELECT Id FROM Task WHERE WhatId = :testCases[0].Id];

		System.assertEquals(insTasks.size(),20);
	}

	@isTest static void test_method_three() {
		// Implement test code
		List<Account> testAccounts = TestClassHelper.createStandardAccs(1);
		Insert testAccounts;

		List<Case> testCases = TestClassHelper.createCases(1, 'low', testAccounts[0].Id);
		Insert testCases;

		List<Task> testTasks = TestClassHelper.createTasks(20, testCases[0].Id);
		Insert testTasks;

		List<Task> insTasks = new List<Task>();
		insTasks = [SELECT Id FROM Task WHERE WhatId = :testCases[0].Id];
		Task task = new Task(Subject='Additional Task',
									Priority = 'Normal',
									Status = 'Not Started',
									Type = 'Other',
									WhatId = testCases[0].Id);
		insTasks.add(task);
		Upsert insTasks;

		insTasks = [SELECT Id FROM Task WHERE WhatId = :testCases[0].Id];

		System.assertEquals(insTasks.size(),21);
	}
	
}

 
Ravi Dutt SharmaRavi Dutt Sharma
You have an empty catch block in your code, so even if any error comes in the backend, it will not surface up to the user screen. I have modified your code a bit - removed try catch block and changed the naming convention so that the code becomes more readble. Can you please try below piece of code and let me know if it works. Thanks.
 
trigger updateCaseTaskCount on Task (after insert,after delete,after update,after undelete) {
    
    Set<ID> caseIds = new Set<ID>();
    String prefix =  '500';
    
    for (Task t : Trigger.new) {
        if (t.WhatId != null && String.valueOf(t.whatId).startsWith(prefix) ) {
            caseIds.add(t.whatId);
        }
    }
    
    for (Task t : Trigger.old) {
        if (t.WhatId != null && String.valueOf(t.whatId).startsWith(prefix) ) {
            caseIds.add(t.whatId);
        }
    }
    
    if (caseIds.size() > 0)
        TaskCountUtility.updateCaseTaskCounts(caseIds);
    
}
 
public with sharing class TaskCountUtility {
    
    public static Boolean didRun = false;
    
    public static void updateCaseTaskCounts(Set<ID> caseIds) {
        
        if (didRun == false) { 
            didRun = true;
            List<Case > cases = [SELECT ID, Activities_Count__c  , (SELECT ID FROM Tasks),(select id from Emails) FROM Case  WHERE ID IN :caseIds];
            List<Case > updateCase = new List<Case>();
            for (Case cs : cases) {
                Integer count = cs.tasks.size();
                if (cs.Activities_Count__c  != count) {
                    cs.Activities_Count__c = count;
                    updateCase.add(cs);
                }
            }
            update updateCase;
        }
    }
}

 
Andrew GAndrew G
Ok, did a deeper dive on the code - i found that my test code was incorrect - i was not testing the activities Count field in the case but the size of the task list, hence why i didn't pick up the issue with the code.  
Once I then tested the field in the test code, it was returning nulls.  So we went to debug logs. (Using System.debug(); extensively)
And then found that I would not get a value for l.tasks.size();
Based on the above I did a rewrite as below:
Basically using the AggregateResult feature to count the tasks. 
Then create a Map so I could grab the Cases using the WhatId on the AggregateResult of Tasks 

The code below would also allow for bulk uploads for Tasks across different Cases.

Hope the below helps
Regards
Andrew
public with sharing class taskCountUtility {

	public static void updateLeadTaskCounts(Set<ID> caseIds) {
 
		AggregateResult[]tasksByCase = [SELECT WhatId, Count(Id) cId FROM Task WHERE WhatId IN :caseIds GROUP BY WhatId];
		List<Case> cases = [SELECT ID, Activities_Count__c  FROM Case  WHERE ID IN :caseIds];
		Map<Id,Case> mapCases = new Map<Id,Case>();
		for (Case cs : cases ) {
			mapCases.put(cs.Id,cs);
		}
		
		List<Case> updateCase = new List<Case>();
		for(AggregateResult ar : tasksByCase ) {
			String tempId = String.valueOf(ar.get('WhatId'));
			Case thisCase = mapCases.get(tempId);  //set the case

			if (thisCase.Activities_Count__c != ar.get('cId')) {
				thisCase.Activities_Count__c = integer.valueof(ar.get('cId'));
				updateCase.add(thisCase);
			}
		}

		if (updateCase.size() > 0 ) {
			update updateCase;
		}
	}
}
and then a sample test code
@isTest static void test_method_three() {
		// Implement test code
		List<Account> testAccounts = TestClassHelper.createStandardAccs(1);
		Insert testAccounts;

		List<Case> testCases = TestClassHelper.createCases(1, 'low', testAccounts[0].Id);
		Insert testCases;

		List<Task> testTasks = TestClassHelper.createTasks(20, testCases[0].Id);
		Insert testTasks;

		Task newtask = new Task(Subject='Additional Task',
									Priority = 'Normal',
									Status = 'Not Started',
									Type = 'Other',
									WhatId = testCases[0].Id);
		Insert newtask;

		List<Task> insTasks = new List<Task>();
		insTasks = [SELECT Id FROM Task WHERE WhatId = :testCases[0].Id];

		List<Case> insCases = new List<Case>();
		insCases = [SELECT Id,Activities_Count__c FROM Case WHERE Id = :testCases[0].Id];

		System.assertEquals(insTasks.size(),21);
		System.assertEquals(insTasks.size(),insCases[0].Activities_Count__c);
	}