+ Start a Discussion
Akash jena 3Akash jena 3 

getting eoor on rollup trigger

trigger TaskCount on Task (after delete, after insert, after undelete, after update) {

Set<ID> Lead__c_Ids = new Set<ID>();

//We only care about tasks linked to Leads.

String leadPrefix = Lead__c.SObjectType.getDescribe().getKeyPrefix();

//Add any Lead ids coming from the new data

if(trigger.new!=null){
    for (Task t : Trigger.new) {
     if (t.WhoId!= null && string.valueof(t.WhoId).startsWith(leadPrefix) ) {

if(!Lead__c_Ids.contains(t.WhoId)){
//adding unique lead ids since there can be many tasks with single lead
Lead__c_Ids.add(t.WhoId);
}
}
      }
}
 
//Also add any Lead ids coming from the old data (deletes, moving an activity from one Lead to another)

if(trigger.old!=null){
    for (Task t2 : Trigger.old) {
     if (t2.WhoId!= null && string.valueof(t2.WhoId).startsWith(leadPrefix) )
         {
if(!Lead__c_Ids.contains(t2.WhoId)){
//adding unique lead ids since there can be many tasks with single lead
Lead__c_Ids.add(t2.WhoId);
}
}
      }
}

     if (Lead__c_Ids.size() > 0){



List<Lead_c> leadsWithTasks = [select id,Task_countc,(select id from Tasks) from Leadc where Id IN : Lead_c_Ids];

List<Lead_c> leadsUpdatable = new List<Lead_c>();

for(Lead__c L : leadsWithTasks){

L.Task_count__c = L.Tasks.size();
leadsUpdatable.add(L);

}

if(leadsUpdatable.size()>0){

update leadsUpdatable;
//update all the leads with activity count

}

    }
}User-added image
ShirishaShirisha (Salesforce Developers) 
Hi Akash,

Greetings!

Seems like the way of referring the Sobject Lead__c_Ids is incorrect.I would suggest you to check the API name of the Object(if it Custom Object).Otherwise,if you referring the Standard Lead Object then it is Lead only.

Please refer the below sample trigger code to count the open activities on Lead Object.
 
trigger UpdateLeadOpenTasks 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 
for(Task t: Trigger.new)
{
 if(string.valueOf(t.WhoId).startsWith('00Q')) LeadIDs.add(t.WhoId); 
System.debug('WhoId = ' + t.WhoId); } 
// Update the Leads 
if(LeadIDs.size()>0)
{ 
for(Lead l: [Select l.Id, l.Open_Tasks__c, (Select Id From Tasks where IsClosed = False) From Lead l where Id in :LeadIDs]
) 
LeadsToUpdate.add(new Lead(Id=l.Id, Open_Tasks__c = l.Tasks.size()));
 update LeadsToUpdate; 
}
 }

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri