+ Start a Discussion
balaji_SFDCbalaji_SFDC 

After the lead Status is changed only new tasks counted

Hi Experts,

I have some confusion on Trigger please let me clarify. Below is my requirement,

I want to update one field(TaskCount) in lead when the task status is completed.I write the trigger for that it's working fine.Below is code


trigger TasksCountUpdateonLead on Task (after insert, after update)

    public set<Id> LeadIDs = new Set<Id>();
    public list<Lead> LeadsToUpdate = new List<Lead>();
    public List<Task> deletetskList=new List<Task>();
   
    //Build the list of Leads to update
    if(Trigger.isInsert || Trigger.isUnDelete || Trigger.isUpdate)
    {
       for(Task tsk: Trigger.new)
       {
           String objName = (tsk.WhoId).getSObjectType().getDescribe().getName();//fetching Object name from id
           system.debug('objName..........'+objName);
           if(objName=='Lead')
           LeadIDs.add(tsk.WhoId);
           system.debug('LeadIDs.....'+LeadIDs);
       }
     }
   
    if(LeadIDs.size()>0)
    {
        for(Lead l: [Select l.Id, l.TaskCount__c,l.Status, (Select Id From Tasks where IsClosed = True) From Lead l where Id in :LeadIDs])
        {
            Lead oldlead = trigger.oldmap.get(l.Id);
            LeadsToUpdate.add(new Lead(Id=l.Id, TaskCount__c = l.Tasks.size()));
            update LeadsToUpdate;
        }
    }
}


Here i want one change When the lead status is changed from 'open-not contacted' to 'closed-converted' the taskcount is reset to zero.after the status is changed to 'closed-converted' the new completed tasks only counted.

     Could you please help me how to achieve this.Thanks in advance

Thanks,
Venkat
 
ForceComForceCom
Hi ,

You can write an aggregate function based on the task status and count the tasks.

Example:
Integer totaltasks;
for(AggregateResult ar: [Select Count(Id) tasksCount , name , status from Task where name ='Your status']){
     totaltasks = (Integer)ar.get('tasksCount');
}

for(Lead l: [Select l.Id, l.TaskCount__c,l.Status, (Select Id From Tasks where IsClosed = True) From Lead l where Id in :LeadIDs]){
Lead oldlead = trigger.oldmap.get(l.Id);
            LeadsToUpdate.add(new Lead(Id=l.Id, TaskCount__c = totalTasks));
            update LeadsToUpdate;
}

I think this might give you an idea.

Thanks.