+ Start a Discussion
adi salesforceadi salesforce 

Trigger to get count of child records in parent object having look up relation

Ashish DevAshish Dev
Just run soql in parent trigger
 
Integer cnt = [Select Count() From Child__c Where Parent__r.Id in :listOfParentRecords];

Let me know if this helps.
Avishek Nanda 14Avishek Nanda 14
Hi Adi,

Assuming cases and task since you have not provided any object name. Case being parent to task. Cretae a custom field on Parent where you would store the count of the child record. We have to make sure When someone adds a record the count should increase at the same time when someone deletes one the count should decrease. So the following trigger am rolling up number of task on case. Please change the object and field as per your need. 

Your helper class should go something like this. 
public class doRollupTask {
    public static void RollupTaskOnCase (List<Task> Tasks){
        Set<Id> CaseIds = new Set<Id>();
        List<Case> CaseListToUpdate = new List<Case>();
        List<Task> lstTaskTempTrigger = New List<Task>();
        
        if(Trigger.isAfter && Trigger.isDelete){
            lstTaskTempTrigger = Trigger.old;
        }else{
            lstTaskTempTrigger = Trigger.new;
        }
        For(Task tsk : lstTaskTempTrigger){
            if(tsk.whatId != null && String.valueOf(tsk.WhatId).startsWith('500')) {
                CaseIds.add(tsk.WhatId);
                System.debug('WhoId' +tsk.WhatId);
            }
        }
        
        For(Case C : [Select Id, Number_of_Tasks__c, (Select Id From Tasks where IsClosed = False) From Case  where Id in :CaseIds]){
            CaseListToUpdate.add(new Case(Id=C.Id, Number_of_Tasks__c  = C.Tasks.size()));
        }
        If(CaseListToUpdate.size() >0){
            Update CaseListToUpdate;
        }
    }
}

Call the Method from Trigger. And you are all set to go. Let me know if this helps. 

Regards,
Avishek Nanda