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
Dev_SfdcDev_Sfdc 

How to show child account count on parent account

How can i show the child account count on the parent account.

 

 

ashishkrashishkr
By child, if you mean the detail in a master-detail relatio, all you need to do is to create a roll-up summary field on the master (parent.) But if you mean a lookup relation, force.com does not give anything out of the box for that. You can create a count field on parent object and write a trigger on your child object which increments this count field everytime a child record is created (after insert) and decrement everytime a child is deleted(before delete.)
Bindhyachal Kumar SinghBindhyachal Kumar Singh

Hi Dev_Sfdc,

 

I think you have to write a trigger on account for insert,update,delete. Make  field on Account first. Child_Count__c

child_count__c 

 

Use following trigger code for you requirement.

trigger countChildAccount on Account (after Insert, after Update, before delete) {
    Set<id> ids= new Set<id>();
    List<Account> acclist = new List<Account>();
    Integer count = 0;
    
    if(Trigger.isInsert || Trigger.isUpdate){
        for(Account acc: Trigger.new){
            if(acc.ParentId!=null)
                ids.add(acc.ParentId);
            acclist.add(acc);
        }
    }
    
    if(Trigger.isDelete){
        for(Account acc: Trigger.old){
            if(acc.ParentId!=null)
                ids.add(acc.ParentId);
            acclist.add(acc);
        }
    }
        
    if(ids.size()>0){
        List<Account> accchild = new List<Account>([select id,Parentid from Account where Parentid IN: ids]);
        List<Account> accparent = new List<Account>([select id,child_count__c from Account where id IN: ids]);
        for(Account ac: accparent){
            count =0;
            for(Account acchild: accchild){
                if(acchild.Parentid == ac.id)
                    count++;
            }
            ac.child_count__c = count;            
        }
        try{
            upsert accparent;
        }catch(DMLException ex){
            System.debug('Exception is '+ex);
        }
    }
}