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>();
        parents.put(c.ParentLookup__c,new Parent__c(id=c.ParentLookup__c));
    for(Child__c c:Trigger.old)
        parents.put(c.ParentLookup__c,new Parent__c(id=c.ParentLookup__c));
  update parents.values();

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

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.