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

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

AI-Driven Trend Analysis: Unlocking Hidden Patterns in Market Data featured image
October 24, 2025
In today's fast-paced financial world, staying ahead of market trends is crucial for investors, traders, and businesses alike. With the exponential growth of data and the rapid advancement of artificial intelligence (AI) technologies, a new frontier has emerged in market analysis: AI-driven trend analysis. This powerful approach is revolutionizing how we interpret market data, uncovering hidden patterns and insights that were previously beyond human comprehension. In this blog post, we'll explore the transformative potential of AI in market trend analysis and its implications for the future of finance.
How AI Chatbots Learn to Handle Complex Customer Questions featured image
October 23, 2025
Artificial intelligence has transformed customer service, with AI chatbots now handling increasingly sophisticated customer inquiries. As customer expectations rise, businesses need chatbots that can go beyond simple FAQs to understand nuanced questions, provide contextual answers, and continuously improve their performance.
How AI Can Help You Automate Repetitive Workflows Effortlessly featured image
October 22, 2025
Repetitive workflows drain productivity, demotivate employees, and create bottlenecks that slow business growth. From data entry and invoice processing to email responses and report generation, these mundane tasks consume valuable time that could be spent on strategic initiatives.