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
lalit kumar 11lalit kumar 11 

Not able to count tasks on account

Hi, 
I am trying to make a count of tasks on a custom field (total_tasks__c) on Account. I am not sure why its not showing the count. Below is the code. 

trigger taskcount on Task (after insert) {
set<id> setid = new set<id>();
list<account> acc3 = new list<account>();

for(task t :trigger.new){
 if(string.valueof(t.whatid).startsWith('OO1') & t.whatid != null)

{
setid.add(t.whatId);    
}
for(account acc1 :[select id,(select id from tasks) total_tasks__c from account where id in:setid]){
if(acc1.Tasks.size()>0)
acc1.total_tasks__c = acc1.tasks.size();
acc3.add(acc1);
}

}
update acc3;
}

Please help to resolve the issue.
Amit Chaudhary 8Amit Chaudhary 8
Please update your code like below
trigger taskcount on Task (after insert) 
{
	set<id> setid = new set<id>();
	for(task t :trigger.new)
	{
		if(  t.whatid != null && string.valueof(t.whatid).startsWith('OO1') )
		{
			setid.add(t.whatId);    
		}
	}
	
	list<account> acc3 = new list<account>();
	for(account acc1 :[select id,total_tasks__c,(select id from tasks)  from account where id in:setid ] )
	{
		if(acc1.Tasks.size()>0)
		{
			acc1.total_tasks__c = acc1.tasks.size();
			acc3.add(acc1);
		}
	}
	if(acc3.size() > 0 )
	{
		update acc3;
	}
	
}
Let us know if this will help you