Anablock Logo

Mastering Salesforce Development: Apex Trigger and Class for Counting Child Records with Lookup Relationships

Himanshu Varshney profile picture
Himanshu Varshney
Senior Salesforce Developer
February 2, 2024

childparent

Apex Trigger: This will be triggered whenever a child record is inserted, updated, or deleted. It will call an Apex Class method to update the count on the parent record.

Apex Class: This class will contain methods to handle the logic for counting the child records and updating the parent record accordingly.

Assuming we have two objects, Parent__c and Child__c, where Child__c has a lookup relationship to Parent__c through a field named Parent__c, and the Parent__c object has a field to store the count of child records named Child_Count__c.


Apex Trigger

trigger ChildTrigger on Child__c (after insert, after update, after delete, after undelete) {
    if (Trigger.isAfter) {
        if (Trigger.isInsert || Trigger.isUndelete) {
            ChildHandler.updateParentCount(Trigger.newMap.keySet(), 'add');
        } else if (Trigger.isDelete) {
            ChildHandler.updateParentCount(Trigger.oldMap.keySet(), 'subtract');
        } else if (Trigger.isUpdate) {
            // For updates, we need to check if the Parent__c field was changed, and then update counts accordingly
            Set<Id> oldParentIds = new Set<Id>();
            Set<Id> newParentIds = new Set<Id>();
            for (Child__c child : Trigger.new) {
                Child__c oldChild = Trigger.oldMap.get(child.Id);
                if (child.Parent__c != oldChild.Parent__c) {
                    if (oldChild.Parent__c != null) oldParentIds.add(oldChild.Parent__c);
                    if (child.Parent__c != null) newParentIds.add(child.Parent__c);
                }
            }
            ChildHandler.updateParentCount(oldParentIds, 'subtract');
            ChildHandler.updateParentCount(newParentIds, 'add');
        }
    }
}


Apex Class

public class ChildHandler {
    public static void updateParentCount(Set<Id> parentIds, String operation) {
        if (!parentIds.isEmpty()) {
            List<Parent__c> parentsToUpdate = new List<Parent__c>();
            for (AggregateResult ar : [
                SELECT Parent__c, COUNT(Id) count
                FROM Child__c
                WHERE Parent__c IN :parentIds
                GROUP BY Parent__c
            ]) {
                Id parentId = (Id)ar.get('Parent__c');
                Integer count = (Integer)ar.get('count');
                Parent__c parent = new Parent__c(Id = parentId);

                if (operation == 'add') {
                    parent.Child_Count__c = count;
                } else if (operation == 'subtract') {
                    parent.Child_Count__c = count - 1; // Assuming the trigger context already removed one child
                }

                parentsToUpdate.add(parent);
            }

            if (!parentsToUpdate.isEmpty()) {
                update parentsToUpdate;
            }
        }
    }
}


Explanation

Trigger: The trigger ChildTrigger is set to fire after insert, update, delete, and undelete operations on Child__c records. Depending on the operation, it calls the updateParentCount method with appropriate parameters.

Apex Class: The ChildHandler class has the updateParentCount method that accepts a set of parent IDs and an operation ('add' or 'subtract'). It queries the Child__c records grouped by Parent__c to get the count, then updates the Parent__c records' Child_Count__c field accordingly.

Make sure to add appropriate error handling and bulkify your code to handle large data volumes efficiently. Also, consider using custom settings or custom metadata types if you need to make your trigger more configurable.

Share this article:
View all articles

Want to learn more about our healthcare solutions?

Discover how our AI technology can transform your healthcare practice.

Related Articles

Blog Post Ideas That Turn Dental Readers Into Booked Appointments featured image
July 15, 2025
Creating compelling blog content is one thing, but crafting posts that actually convert readers into booked appointments is an art form that many dental practices struggle to master. While having an active blog demonstrates expertise and improves SEO, the ultimate goal should be turning those website visitors into patients sitting in your chair.
How CRM Systems Can Improve Patient Experience in Dentistry featured image
July 14, 2025
Customer Relationship Management systems in dentistry are specialized software platforms designed to manage all aspects of patient interactions and data. Unlike generic business CRMs, dental-specific systems integrate clinical workflows, treatment planning, and regulatory compliance requirements. These platforms consolidate patient information, communication history, treatment records, and financial data into a unified system that enables practices to deliver personalized, efficient care.
Why Every Dental Clinic Needs a Fast, Modern Website featured image
July 11, 2025
In an era where patients research healthcare providers online before making their first appointment, your dental clinic's website serves as your digital front door. A fast, modern website isn't just about aesthetics, it's a powerful tool that directly impacts patient acquisition, retention, and practice growth.