You need to sign in to do that
Don't have an account?

Apex trigger for updating open task count of leads
I want to write a trigger to update the open task count of leads
Trigger:
trigger UpdateLeadOpenTasksCount on Task (after delete, after insert, after undelete, after update) {
// Declare the variables
public set<Id> LeadIDs = new Set<Id>();
public list<Lead> LeadsToUpdate = new List<Lead>();
// Build the list of Leads to update
if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate){
for(Task t: Trigger.new){
if(t.WhoId != NULL && string.valueOf(t.WhoId) != NULL && string.valueOf(t.WhoId).startsWith('00Q'))
LeadIDs.add(t.WhoId);
}
}
if(Trigger.isDelete || Trigger.isUpdate){
for(Task t: Trigger.old){
if(t.WhoId != NULL && string.valueOf(t.WhoId) != NULL && string.valueOf(t.WhoId).startsWith('00Q'))
LeadIDs.add(t.WhoId);
}
}
// Update the Leads
if(LeadIDs.size()>0){
for(Lead l: [Select l.Id, l.Open_Tasks_Count__C,
(Select Id From Tasks where IsClosed = False)
From Lead l where Id in :LeadIDs])
LeadsToUpdate.add(new Lead(Id=l.Id, Open_Tasks_Count__C = l.Tasks.size()));
update LeadsToUpdate;
}
}
But still many leads are not updating except a few. Can anyone help on this. It needs to check each and every lead already existed and newly upcoming leads and check if there is any activity and update the count. If anyone have any other existing trigger to solve this purpose please post it along with the test code. Thank you in advance.
Teja,
Most of Tasks even though they show opened, but they may go into archieved, so work on that too.
I didn't get exactly what your mentioning. Can you please elaborate on this or help me with the sample code atleast how i should include them too. Thanks in advance.