Count Records in a Related List using Apex

Count Records in a Related List using Apex

Last Updated on October 17, 2021 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. Without using roll-up summary field, then this blog post is for you.

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 on Parent Object

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 on Child Object

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.

Formative Assessment:

I want to hear from you!  

What is one thing you learned from this post? How do you envision applying this new knowledge in the real world? 

Let me know by Tweeting me at @automationchamp, or find me on LinkedIn.

Have feedback, suggestions for posts, or need more information about Salesforce online training offered by me? Say hello, and leave a message!

Preferred Timing(required)

2 thoughts on “Count Records in a Related List using Apex

Leave a Reply

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

Discover more from Automation Champion

Subscribe now to keep reading and get access to the full archive.

Continue reading