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

by Himanshu Varshney, Senior Salesforce Developer

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.

More articles

Ethical Considerations in AI Development

In the realm of artificial intelligence (AI), the pace of innovation has far outstripped the development of ethical guidelines and frameworks. As AI systems become increasingly integral to our daily lives, from personal assistants to decision-making algorithms, the imperative to address ethical considerations in AI development has never been more pressing. This blog post explores the multifaceted ethical landscape of AI development, underscored by a poignant use case that brings to light the complex interplay of ethics, technology, and human values

Read more

Transforming Professional Presence with Anablock's Headshots: A Game-Changer for Personal Branding

In an era where digital presence is synonymous with professional identity, Anablock's Headshots emerges as a revolutionary tool designed to elevate individual branding through high-definition, AI-generated professional headshots. This application caters to a broad spectrum of users, from job seekers to corporate executives, offering them a seamless pathway to enhancing their online profiles across platforms like LinkedIn, company websites, and professional portfolios

Read more

Ready to get started?

Our offices

  • San Francisco
    353 Sacramento Street
    San Francisco, CA 94111
  • Walnut Creek
    2121 N California Blvd
    Walnut Creek, CA 94596