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
Akash jena 3Akash jena 3 

getting error in 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_count__c,(select id from Tasks) from Lead__c 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

}

    }
}
ShirishaShirisha (Salesforce Developers) 
Hi Akash,

Greetings!

Please refer the sample code provided below and make changes according to your requirement:
 
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