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
CRJ2011CRJ2011 

Counting child records in Account hierarchial relation.

In my scenario one account has many child account records (heirarchial relation) . I want to count these child records. 

I am very new Apex and salesforce . Please guide.

Ritesh AswaneyRitesh Aswaney

assuming a parent - child (2 level hierarchy)

 

trigger AccountAfter on Account (after insert, after update){

 

Set<Id> parentAccs = new Set<Id>{};

Map<Id, Integer> childCount = new Map<Id, Integer>{};

 

for (Account a : trigger.new)

if(a.ParentId != null)

parentAccs.add(a.ParentId);  //collect parent ids

 

for(Account acc : [Select Id, ParentId from Account where ParentId IN :parentAccs]){

if(childCount.get(acc.ParentId) == null)

childCount.put(acc.ParentId, 0);  //create a counter for parent

 

childCount.put(acc.ParentId, childCount.get(acc.ParentId) +1); //increment counter

 

}

 

List<Account> accsUpdate = new List<Account>{};

 

for(Id accId : childCount.keySet())

accsUpdate.add(new Account(Id = accId, ChildCount__c = childCount.get(accId))); //set parent counts

 

if(accsUpdate != null && !accsUpdate.isEmpty())

Database.update(accsUpdate); //update parent accounts

}

CRJ2011CRJ2011

Thanks ..

Venkatesh C 7Venkatesh C 7
@Ritesh Aswaney
If all the Child account has the same picklist field value, then the parent should be populated with the same value as the child

Could you please help me on this.

Thanks
balagani.rakeshbabu@gmail.com