trigger TaskRollUpOnContact on Task (after insert, after update, after delete, after undelete) { list listTask = new list() ; set setContactWhoId = new set() ; if(Trigger.isInsert){ for(Task oTask : Trigger.New){ if(oTask.Status == 'Completed') setContactWhoId.add(oTask.WhoId) ; } } system.debug('after insert-setContactWhoId:: ' + setContactWhoId) ; if(Trigger.isUpdate){ for(Task oTask : Trigger.New){ if(oTask.Status == 'Completed' && oTask.Status != Trigger.oldMap.get(oTask.Id).Status) setContactWhoId.add(oTask.WhoId) ; } } system.debug('after update-setContactWhoId:: ' + setContactWhoId) ; if(Trigger.isDelete){ for(Task oTask : Trigger.Old){ if(oTask.Status == 'Completed') setContactWhoId.add(oTask.WhoId) ; } } system.debug('after delete-setContactWhoId:: ' + setContactWhoId) ; if(Trigger.isUndelete){ for(Task oTask : Trigger.New){ if(oTask.Status == 'Completed') setContactWhoId.add(oTask.WhoId) ; } } system.debug('after undelete-setContactWhoId:: ' + setContactWhoId) ; if(!setContactWhoId.isEmpty()){ list listContactToUpdate = new list() ; list listContact = [Select Id, No_of_Completed_Task__c, (Select Id From Tasks Where Status = 'Completed') From Contact Where Id IN: setContactWhoId] ; if(listContact != null && !listContact.isEmpty()){ for(Contact oContact : listContact){ oContact.No_of_Completed_Task__c = oContact.Tasks.size() ; listContactToUpdate.add(oContact) ; } } if(!listContactToUpdate.isEmpty()) update listContactToUpdate ; } }