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

Retargeting Campaigns for Dental Clinics: Bring Back Lost Leads featured image
August 7, 2025
In the competitive landscape of dental marketing, losing potential patients who visit your website but don't book appointments is a costly missed opportunity. Retargeting campaigns offer a powerful solution to reconnect with these lost leads, bringing them back into your patient acquisition funnel.
Text Message Reminders: Small Change, Big Impact on No-Shows featured image
August 6, 2025
This seemingly small technological upgrade delivers outsized returns, dramatically reducing missed appointments while simultaneously improving patient satisfaction and practice efficiency. As practices navigate an increasingly digital healthcare landscape, SMS reminders have evolved from a nice-to-have feature to an essential component of modern patient communication strategies.
The Psychology Behind Dental Fear - and How Marketing Can Help featured image
August 5, 2025
This blog post by Anablock explores the psychological foundations of dental fear and provides actionable marketing strategies to help practices connect with anxious patients, reduce barriers to care, and build thriving practices based on trust and understanding.