You need to sign in to do that
Don't have an account?
SFDC@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.
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); }
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
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 and then a sample test code