+ Start a Discussion
CBBsfdcCBBsfdc 

Trigger to count number of contacts associated with an account

Hi all, 

I want to display Whenever Contacts are inserted, updated, deleted, and undeleted then Count should get rolled-up on Accounts.
 for this I had created a check box field like contact_roll_c and in contact field and number field like No_Of_Active_Contacts__c in Account object 

trigger updateAccount on Account (before Update) {

List<Contact> Contactlist=[select id,name,phone,accountid from contact where accountID In :trigger.new ];
map<id,integer> countMap=new map<id,integer>();
integer i=1;
for(contact c:contactlist)
{
       if(countmap.containskey(c.accountid))
       {
           i=countmap.get(c.accountid)+1;
           countmap.put(c.accountid,i);
       }
       else
       {
              countMap.put(c.accountid,i);
       }
}

for(account a:trigger.new)
{
try{
        if(countmap.containskey(a.id))
            a.Contact_Count__c=countMap.get(a.id);
   }
   catch(exception e)
   {
  
   }
}
}


Kindly support and suggest.

Thanks
Khan AnasKhan Anas (Salesforce Developers) 
Hi,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.
 
trigger CountConOnAcc on Contact (after insert, after update, after delete) {
    
    Set <Id> accountIds = new Set <Id>();
    List <Account> lstAccountsToUpdate = new List <Account>();
    
    if(Trigger.isInsert){
        for(Contact con:trigger.new){
            accountIds.add(con.accountID);
        }
    }
    
    if(Trigger.isUpdate|| Trigger.isDelete){
        for(Contact con:trigger.old){
            accountIds.add(con.accountID);
        }
    }
    
    for(Account acc:[SELECT Id,Name,No_Of_Active_Contacts__c,(Select Id from Contacts) from Account where Id IN: accountIds]){
        Account accObj = new Account ();
        accObj.Id = acc.Id;
        accObj.No_Of_Active_Contacts__c = acc.Contacts.size();
        lstAccountsToUpdate.add(accObj);
    }
    
    if(lstAccountsToUpdate.size()>0){
    	UPDATE lstAccountsToUpdate;
    }
}

No need to create a checkbox field.

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Deepali KulshresthaDeepali Kulshrestha
Hi,

trigger ContactSumTrigger on Contact (After insert, After delete, After undelete) {
    Set<Id> parentIdsSet = new Set<Id>();
    List<Account> accountListToUpdate = new List<Account>();
    IF(Trigger.IsAfter){
        IF(Trigger.IsInsert || Trigger.IsUndelete){
            FOR(Contact c : Trigger.new){
                if(c.AccountId!=null){   
                   parentIdsSet.add(c.AccountId); 
                }
            }
        }
        IF(Trigger.IsDelete){
            FOR(Contact c : Trigger.Old){
                if(c.AccountId!=null){   
                   parentIdsSet.add(c.AccountId); 
                }
            }
        }
    }
    System.debug('#### parentIdsSet = '+parentIdsSet);
    List<Account> accountList = new List<Account>([Select id ,Name, Number_of_Contacts__c, (Select id, Name From Contacts) from Account Where id in:parentIdsSet]);
    FOR(Account acc : accountList){
        List<Contact> contactList = acc.Contacts;
        acc.Number_of_Contacts__c = contactList.size();
        accountListToUpdate.add(acc);
    }
    try{
        update accountListToUpdate;
    }catch(System.Exception e){
        
    }
}
For more information refer to these links:
https://success.salesforce.com/answers?id=9063A000000e0GiQAI
https://developer.salesforce.com/forums/?id=906F0000000AcdaIAC

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha