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
tejateja 

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.

Suresh RaghuramSuresh Raghuram

Teja,

Most of Tasks even though they show opened, but they may go into archieved, so work on that too.

tejateja

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.

Suresh RaghuramSuresh Raghuram
If you do query all from the data loader you will get all the tasks, if you do just query you will get only few records. this is because. after two years time period most of the records under go archieved. From this what i would like to say is even if you do query from the apex you will get only few records and few records will not be shown. So I asked you to check on this