Count records in a related list

Last Updated on November 12, 2017 by Rakesh Gupta

If you want to populate a field with the count of the number of records in a specific related list on a custom object.

Note:- Without using roll-up summary field

I will suggest two triggers. First trigger on the child object (to cause a parent-level trigger), and a second trigger to update the field.

trigger OnParent on Child__c (after insert, after update, after delete, after undelete) {
  Map<Id,Parent__c> parents = new Map<Id,Parent__c>();
  if(Trigger.new<>null)
    for(Child__c c:Trigger.new)
      if(c.ParentLookup__c<>null)
        parents.put(c.ParentLookup__c,new Parent__c(id=c.ParentLookup__c));
  if(Trigger.old<>null)
    for(Child__c c:Trigger.old)
      if(c.ParentLookup__c<>null)      
        parents.put(c.ParentLookup__c,new Parent__c(id=c.ParentLookup__c));
  update parents.values();
}


trigger Onchild on Parent__c (before insert, before update) {
  for(Parent__c p:Trigger.new)
    p.RollupCounter__c = 0;
  for(Child__c c:[select id,ParentLookup__c from Child__c where ParentLookup__c in :Trigger.new])
    Trigger.newMap.get(c.ParentLookup__c).RollupCounter__c++;
}

The child trigger is responsible for making sure that both the old parent and new parent (if there is change) has their values updated accordingly. The parent trigger actually performs the tallying.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.