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

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

//adding unique lead ids since there can be many tasks with single lead
//Also add any Lead ids coming from the old data (deletes, moving an activity from one Lead to another)

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

     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();



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


ShirishaShirisha (Salesforce Developers) 
Hi Akash,


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:
 if(string.valueOf(t.WhoId).startsWith('00Q')) LeadIDs.add(t.WhoId); 
System.debug('WhoId = ' + t.WhoId); } 
// Update the Leads 
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