function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Abhishek chauhan 20Abhishek chauhan 20 

"A" child record had parent A & "B" record had parent "B". ,, if we update the parent of Child Record A to Parent B then i want to update the total child count filed in parent obj = 1+1 = 2 and in other parent 1-1 = 0

Sai PraveenSai Praveen (Salesforce Developers) 
Hi Abhishek,

You can try the logic as below.

Replace Child_Object__c with your child object Name and Parent_Object__c with your parent object API name and 
trigger UpdateChildCount on Child_Object__c (after update) {
   
    Map<Id, Id> oldParentMap = new Map<Id, Id>();
    Map<Id, Id> newParentMap = new Map<Id, Id>();
    for (Child_Object__c child : Trigger.new) {
        if (child.Parent__c != Trigger.oldMap.get(child.Id).Parent__c) {
            oldParentMap.put(child.Id, Trigger.oldMap.get(child.Id).Parent__c);
            newParentMap.put(child.Id, child.Parent__c);
        }
    }
    
    
    Map<Id, Parent_Object__c> parentMap = new Map<Id, Parent_Object__c>([
        SELECT Id, Name, Child_Count__c
        FROM Parent_Object__c
        WHERE Id IN :oldParentMap.values() OR Id IN :newParentMap.values()
    ]);
    for (Child_Object__c child : Trigger.new) {
        if (oldParentMap.containsKey(child.Id)) {
            parentMap.get(oldParentMap.get(child.Id)).Child_Count__c--;
        }
        if (newParentMap.containsKey(child.Id)) {
            parentMap.get(newParentMap.get(child.Id)).Child_Count__c++;
        }
    }
    update parentMap.values();
}

Let me know if you face any issues.

If this solution helps, Please mark it as best answer.

Thanks,