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
sfdc loginsfdc login 

1. Assuming there is a field on Account : ‘Total Contacts’. Write a trigger on Contact to update Account with Total Contacts associated. (This should handle Bulk Insert/Deletes)

rajat Maheshwari 6rajat Maheshwari 6

Hi sfdc,

Please find below code snippet, Hope it will helps you :)

trigger countTrigger on contact(after insert,afterDelete) { 

Set<Id> st_AccountId = new Set<Id>(); 

if(Trigger.isAfter && Trigger.isInsert)
 { 
for (Contact con: Trigger.new) 
  {
st_AccountId.add(con.accountid); 
   } 
  }

  if(Trigger.isAfter && Trigger.isDelete) 
    { 
      for (contact con_Del : Trigger.old) 
         { 
            st_AccountId.add(con_Del.accountId); 
         } 
    } 

Map<Id,Double> count_Map = new Map<Id,Double>(); 
List<Account> AccountToUpdate = new List<Account>();

 for(AggregateResult results = [Select accountId,Count(Id) FROM Contact where accountId IN: st_AccountId GROUP BY accountId])
   { 
     count_Map.put((Id)results.get('accountId'), (Double)results.get('expr0')); 
   } 

for(Account acct: [SELECT Id,Total Contacts FROM Account WHERE Id IN :st_AccountId ]) 
  { 
    if(count_Map!=null && count_Map.containsKey(acct.Id)) 
        { 
           acct.Total Contacts= (Double)count_Map.get(acct.id); 
           AccountToUpdate.add(acct); 
         } 
  } 

if(AccountToUpdate!=null && AccountToUpdate.size()>0) 
    update AccountToUpdate; 

}

Note : Here Please relpace the "Total Contacts" by API Name of Total contact field in code.

Thanks
Rajat Maheshwari
rajatzmaheshwari@gmail.com