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
Raghavendra Sharma 12Raghavendra Sharma 12 

hi i am new in salesforce, i want to achieve roll up summary functionality through trigger, please help me and i want to count no of child record associated to parent, and update a field of parent object which hold no of child record associated with that

v varaprasadv varaprasad
Hi Raghavendra,

Please check once below code it will count the number of contacts on account record.

Trigger on contact object : 
trigger RollupSummaryTriggerOnAccountObj on contact(after insert, after update, after delete, after undelete) {  
    if (trigger.isAfter && (trigger.isInsert || trigger.isUpdate || trigger.isUndelete)) {
        SampleRollupSummary.rollupContacts(trigger.new);
    }
    else if (trigger.isAfter && trigger.isDelete) {
        SampleRollupSummary.rollupContacts(trigger.old);
    }
}

Related class :
 
public class SampleRollupSummary {
    
   public static void rollupContacts(list<contact> lstOfconts){
       system.debug('==lstOfconts== : '+lstOfconts);
       set<id> accIds = new set<id>();
       list<account> updLstOfAccs = new list<account>();     
       
       for(contact con : lstOfconts){
           accIds.add(con.accountid);
       }
       system.debug('==accIds==:'+accIds);
       list<account> lstAccs = [select id,name,Total_Count__c, (select id from contacts) from account where id in : accIds];
       
       for(account acc : lstAccs){
           system.debug('==acc.contacts.size()=='+acc.contacts.size());
           acc.Total_Count__c = acc.contacts.size();
           updLstOfAccs.add(acc);
       }
       if(updLstOfAccs.size() > 0){
           update updLstOfAccs;
       }
       
       
    }

}

I hope it helps you.
If it helps you please mark it as the best answer in case of any other assistance please feel free to contact me.


Thanks
Varaprasad