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
sagar077sagar077 

Create an apex trigger that will count number of contacts associated with an account(create a field at account level) . Must update the count in insertion and deletion of a contact by using Map.

Create an Apex trigger that will count the number of contacts associated with an account(create a field at account level). Must update the count in insertion and deletion of contact by using MAP Collection.
ANUTEJANUTEJ (Salesforce Developers) 
Hi Sagar,

Could you please look at the below link that could help as it has a similar implementation.

>> https://salesforce.stackexchange.com/questions/138455/count-the-contacts-in-the-related-list-of-account-and-display-the-contact-count/178118

The code in the above link is 
trigger CountContactOnAccount 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,Count_Contact__c,(Select Id from Contacts) from Account where Id IN: accountIds]){
    Account accObj = new Account ();
    accObj.Id = acc.Id;
    accObj.Count_Contact__c = acc.Contacts.size();
    lstAccountsToUpdate.add(accObj);
}

UPDATE lstAccountsToUpdate;

I hope this helps and in case if this came inhandy can you please choose this as best answer so that it can be used by others in the future.

Regards,
Anutej
sagar077sagar077
Hello Anutej,

Thanks for the help, but I want same code using Map also

Thanks,
Sagar 
ANUTEJANUTEJ (Salesforce Developers) 
I think you would be able to use the above as reference and implement using a map, also is there any reason why this needs to he done using a map as this does the same functionality.
sagar077sagar077
Hello All,

I am done with using map but i am unable to complete one case ie- if account having associated  with 2 contacts and I changed the Account Name 'A' to Account 'B' then the count of contact fields not update the count of contact.

Pleases help me in code
Thanks 

trigger AccountCountContactMap on Contact (after insert,after update, after delete)
{
        Map <Id, List<Contact>> mapAcctIdContactList = new Map <Id, List<Contact>>();
        Map <Id, List<Contact>> mapAcctIdDelContactList = new Map <Id, List<Contact>>();
    
        Set<Id> AcctIds = new Set<Id>();
        List<Account> listAcc = new List<Account>();
      
    if(trigger.isinsert)
        {
            for(Contact Con : trigger.new)
                {
                    if(string.isNotBlank(Con.AccountId))
                    {
                        if(!mapAcctIdContactList.containsKey(Con.AccountId))
                        {
                            mapAcctIdContactList.put(Con.AccountId, new List<Contact>());        
                        }
                            mapAcctIdContactList.get(Con.AccountId).add(Con);
                            AcctIds.add(Con.AccountId);
                    }
                }
        }
    
    if(trigger.isupdate)
    {
        for(Contact Con:trigger.new)
            {
                 if(string.isNotBlank(Con.AccountId) && Con.AccountId !=trigger.oldmap.get(Con.Id).AccountId)
                    {
                        if(!mapAcctIdContactList.containsKey(Con.AccountId))
                        {
                            mapAcctIdContactList.put(Con.AccountId, new list <Contact>());
                        }
                            mapAcctIdContactList.get(Con.AccountId).add(Con);
                            AcctIds.add(Con.AccountId);
                   }
                    else if(string.isBlank(Con.AccountId) && string.isNotBlank(trigger.oldmap.get(Con.Id).AccountId))
                        {
                            if(!mapAcctIdDelContactList.containsKey(Con.AccountId))
                            {
                                 mapAcctIdDelContactList.put(Con.AccountId,new list<Contact>());   
                            }
                          mapAcctIdDelContactList.get(Con.AccountId).add(Con);
                          AcctIds.add(trigger.oldMap.get(Con.Id).AccountId);
                        }
            }
    }
 
     if(trigger.isdelete)
         {
            for(Contact Con : trigger.Old)
                {
                    if(string.isNotBlank(Con.AccountId))
                        {
                            if(!mapAcctIdDelContactList.containsKey(Con.AccountId))
                                {
                                    mapAcctIdDelContactList.put(Con.AccountId, new List<Contact>());
                                }
                            mapAcctIdDelContactList.get(Con.AccountId).add(Con);
                            AcctIds.add(Con.AccountId);
                        }
                }
         }
    
    if(AcctIds.size() > 0)
        {
            listAcc =[Select Id,Number_Of_Contact_Count__c from Account where Id in : AcctIds];
            for(Account acct : listAcc)
                {
                    Integer noofConts=0;
                    if(mapAcctIdContactList.containsKey(acct.Id))
                        {
                            noofConts += mapAcctIdContactList.get(acct.Id).size();
                        }
                    if(mapAcctIdDelContactList.containsKey(acct.Id))
                        {
                            noofConts -= mapAcctIdDelContactList.get(acct.Id).size();    
                        }
                    acct.Number_Of_Contact_Count__c = acct.Number_Of_Contact_Count__c == null ? noOfConts : (acct.Number_Of_Contact_Count__c + noOfConts);
                }
            update listAcc;
        }
}

 
Simran KhatriSimran Khatri
You have to add one more line in update case to store the old Account id as well  ---- mapAcctIdContactList.put(oldMap.get(conObj.Id).AccountId, new list <Contact>());