+ Start a Discussion
srikanth j 24srikanth j 24 

Display Contacts Associated with Account

Hi Evry1,
I Have a Requirement Using Trigger When a account is record updated need to display all contacts associated with that account
can anyone help me out if possible send me code
NagendraNagendra (Salesforce Developers) 
Hi Srikanth,

If you want to display the “Total Number of Contacts” for each “Account” in Salesforce on the Account page you can not use the Roll-Up Summary field. The Roll-Up Summary fields on contact are not supported on Accounts. We have used a Trigger on the contact object to  find the sum of the number of contacts which are there in an Account.

The trigger basically updates the Account custom field “Number_of_contacts__c” with the number of contacts that Account has. Since this trigger is on the Standard object it can be used in any Salesforce.com ORG by creating this custom field on Account.

Please find the code snippet below which suits your requirement.

trigger ContactsOnAccount on Contact (after insert, after delete,after undelete,after update) { Set aId = new Set(); if(Trigger.isInsert || Trigger.isUndelete){ for(Contact opp : Trigger.New){ aId.add(opp.AccountId); } List acc = [select id,No_of_Contacts_in_SFDC__c from Account where Id in:aId]; List con = [select id from contact where AccountId in :aId]; for(Account a : acc){ a.No_of_Contacts_in_SFDC__c=con.size(); }update acc; } if(Trigger.isDelete){ for(Contact opp : Trigger.old){ aId.add(opp.AccountId); } List acc = [select id,No_of_Contacts_in_SFDC__c from Account where Id in:aId]; List con = [select id from contact where AccountId in :aId]; for(Account a : acc){ a.No_of_Contacts_in_SFDC__c=con.size(); }update acc; } if(Trigger.isUpdate){ Set OldAId = new Set(); for(Contact opp : Trigger.new){ if(opp.AccountId != Trigger.oldMap.get(opp.id).AccountId || opp.Primary_Contact__c != Trigger.oldMap.get(opp.id).Primary_Contact__c) aId.add(opp.AccountId); OldAId.add(Trigger.oldMap.get(opp.id).AccountId); } if(!aId.isEmpty()){ //for new Accounts List acc = [select id,No_of_Contacts_in_SFDC__c from Account where Id in:aId]; //For New Account Contacts List con = [select id from contact where AccountId in :aId]; /* This is For Old Contacts Count */ //for Old Accounts List Oldacc = [select id,No_of_Contacts_in_SFDC__c from Account where Id in:OldAId]; //For Old Account Contacts List OldCon = [select id from contact where AccountId in :OldAId]; //For New Accounts for(Account a : acc){ a.No_of_Contacts_in_SFDC__c=con.size(); }update acc; //For Old Accounts for(Account a : Oldacc){ a.No_of_Contacts_in_SFDC__c=OldCon.size(); }update Oldacc; } }
}


It works on delete of a contact and it also works even if you change the Account of a contact where it updates both the Accounts with the number of contacts.

Please mark this as best answer if this helps.

Best Regards,
Nagendra.P