Skip to content
  • linkedIn
  • twitter
  • About Us
  • News letter
  • Privacy Policy
  • Contact Us
sfdcgenius

sfdcGenius

Learn Practice and Execute

salesforce
  • Home
  • Blog
  • Apex
  • Toggle search form
Write a trigger to count the number of related child records on parent records.

Write a trigger to count the number of related child records on the parent.

Posted on April 3, 2022January 19, 2023 By sfdcGenius 1 Comment on Write a trigger to count the number of related child records on the parent.

Write a trigger to count the number of related child records on parent records.
Custom Rollup Summary Field Using Apex Trigger.
Create Rollup Summary on the Lookup relationship using a trigger.

All the above 3 are three different ways to ask the same question.

Let’s take an example to understand the problem and then will write a trigger.
Account and Contacts are lookup relationships. We have to count the number of child records associated with each account.

Table of Contents

    • While counting the number of child records we need to consider a few scenarios before writing a trigger
  • Note:
  • Apex Trigger
  • Trigger Helper Class (Apex Class)

While counting the number of child records we need to consider a few scenarios before writing a trigger

  1. When any new child record is inserted, we need to update the rollup summary field on the parent record. (After Insert)
  2. When the parent id is updated on the child record, we need to update the rollup summary field on the parent record. (After Update)
  3. For any child record deleted, we need to update the rollup summary field on the parent record. (Before Delete)
  4. For any child record undeleted, we need to update the rollup summary field on the parent record. (After Undelete)

Note:

  • Always follow salesforce best practices while writing code. (Apex Trigger and Apex Class(Trigger Helper class )
  • For after update always query both old and new parent records to update the count. We generally query only new parent records.
  • Write a trigger to count the number of related child records on parent records.

Apex Trigger

trigger RollUpCountTrigger on Contact (after insert, after update, after delete, after undelete) {
    //when child record inserted and undeleted
    if(trigger.isAfter && (trigger.isInsert || trigger.isUndelete)){
        RollUpCountTrigger.countContact(trigger.new);
    }
    else if(trigger.isAfter && trigger.isDelete){ // when child record deleted
        RollUpCountTrigger.countContact(trigger.old);
    }
    if(trigger.isAfter && trigger.isUpdate){ //when parent id updated on child records
        RollUpCountTrigger.countContactUpdate(trigger.new,trigger.oldMap);
    }
}

Trigger Helper Class (Apex Class)

public class RollUpCountTrigger {
    
    public static void countContact(List<Contact> newList){ //for insert, undelete and undelete
        Set<id> accountIds = new Set<id>();
        List<Account> listOfAccounts = new List<Account>();
        
        For(Contact con : newList){   
            if(con.AccountId != null){
                accountIds.add(con.accountId);  //new parent id         
            }     
        }            
        if(!accountIds.isEmpty()){
            List<Account> listAccount = [SELECT Id, Name, Number_of_Contacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :accountIds];
            For(Account acc : listAccount){
                if(acc.Contacts.size()>0)
                    acc.Number_of_Contacts__c = acc.Contacts.size(); // count of child records
                listOfAccounts.add(acc);
            }
            if(listOfAccounts.size()>0)
                update listOfAccounts; //update parent records
        }
        
    }
    
    public static void countContactUpdate(List<Contact> newList,Map<Id,Contact> oldMap){  //for update
        Set<id> accountIds = new Set<id>();
        List<Account> listOfAccounts = new List<Account>();
        
        For(Contact con : newList){   
            if(con.AccountId != null){
                accountIds.add(con.accountId); // new parent id           
            }
            if(con.AccountId != oldMap.get(con.Id).AccountId){
                accountIds.add(oldMap.get(con.Id).AccountId);  // old parent id 
            }   
        }            
        if(!accountIds.isEmpty()){
            List<Account> listAccount = [SELECT Id, Name, Number_of_Contacts__c, (SELECT Id FROM Contacts) FROM Account WHERE Id IN :accountIds];
            For(Account acc : listAccount){
                if(acc.Contacts.size()>0)
                    acc.Number_of_Contacts__c = acc.Contacts.size(); // count of child records
                listOfAccounts.add(acc);
            }
            if(listOfAccounts.size()>0)
                update listOfAccounts; // update parent records
        }  
    }
}

What are Apex Triggers in Salesforce?

For any Queries/doubts comment below and for quick responses on LinkedIn and Twitter.

Related Post

Apex, Apex Class, Apex Triggers, Customization, Recent Post Tags:Apex Class, Apex Trigger, Apex Trigger Basic Question, Apex Trigger Example, Create Rollup Summary on Lookup relationship using trigger., Custom Rollup Summary Field Using Apex Trigger., Lookup relationship salesforce, Salesforce, Trigger, Write a trigger to count number of related child record on parent records. Custom Rollup Summary Field Using Apex Trigger.

Post navigation

Previous Post: How to check whether record values are changed or not in Apex Triggers
Next Post: Lightning Web Component Life Cycle

Comment (1) on “Write a trigger to count the number of related child records on the parent.”

  1. Unkown says:
    July 23, 2022 at 5:21 pm

    I simply couldn’t depart your web site prior to suggesting
    that I extremely enjoyed the standard information an individual supply to your
    guests? Is gonna be back continuously to inspect new posts

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Categories

  • Admin
  • Apex
  • Apex Class
  • Apex Triggers
  • Customization
  • Flow
  • Lightning Web Component
  • Ligthing
  • LWC
  • Recent Post
  • Salesforce Security

Tags

@api @track @wire Admin Apex Apex Class Apex Trigger api connectedCallback() decorators disconnectedCallback disconnectedCallback() errorCallback errorCallback() Flow How to check whether record values are changed or not in Apex Trigger how to create modal in lwc how to create popup in lwc lighting flow LightningAlert LightningConfirm LightningPrompt lightning web component lwc modal/popup in lwc Modal in lwc notification in lwc popup in lwc renderedCallback() Role Hierarchies Salesforce Salesforce Customization salesforce flow salesforce latest update salesforce layoff sfdc sfdcGenius sfdcginus track trailhead Trigger.NewMap Vs Trigger.oldMap trigger.old vs Trigger.New wire wrapper class in apex wrapper class in salesforce

Resources

  • About Us
  • Blog
  • Contact Us
  • Home
  • Newsletter
  • Privacy Policy

Social Media

  • linkedIn
  • twitter

Copyright © 2025 sfdcGenius.

Powered by PressBook WordPress theme