"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
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.
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
Let me know if you face any issues.
If this solution helps, Please mark it as best answer.
Thanks,