+ Start a Discussion
Srujana D 7Srujana D 7 

How to Create Rollup summary By Using Triggers?

hi
Iam New to salesforce Development
Niharika GoudNiharika Goud
Hai Srujana
Once Look into below link 
https://developer.salesforce.com/forums/?id=906F00000008yWuIAI
v varaprasadv varaprasad
Hi Srujana,

Please look into the below sample code : 
 
Trigger :

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);
    }
}


its 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>();
        list<contact> lstCons = new list<contact>();
       
        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;
        }
       
       
    }
   
}


Hope this helps you.

Please let me know in case of any other assistance.



Thanks
Varaprasad
For Support : varaprasad4sfdc@gmail.com