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
Harish PHarish P 

Trigger on account object to display count of related contacts when we update account..., plz send code for this

Sean FieldingSean Fielding
What is your use case?  Are you sure you need/want a trigger on the account object?  It seems instead you would want a trigger on the contact objects firing
- on insert where accountId is populated
- on update where accountId is updated (firing two rollups if account id is changing from one value to another)
Harish PHarish P
Yes, I want trigger on Account object. Using after update and after insert, i need to trigger to get number of contacts in count. That should be displayed in account.
sfdc TrailHeadssfdc TrailHeads

trigger RollupSummarytrigger on Contact (after insert, after update, after delete) {
Set<Id> accIds = new Set<Id>();
for (Contact c:
Map<id,Account> mapAcc = new Map<id,Account>([Select Name,NumberOfContacts__c,(Select Id from Contacts) from Account WHERE Id in: accIds ]);
for (Account a: mapAcc.values())
mapAcc.get(a.Id).NumberOfContacts__c =a.Contacts.size();
System.debug('Number of contacts:'+mapAcc.get(a.Id).NumberOfContacts__c);
update mapAcc.values();
Harish PHarish P
Hi...., Thanks for sharing views, But i want trigger on account like (Trigger Trigger_Name On Account(After insert, After update) For count the contacts and display account object custom field...., Plz share ur views
sfdc TrailHeadssfdc TrailHeads
Hi Harsh,
//trigger on Account
trigger NumberContactsOnaccountUsingAccUpdtInsert on Account (before update)
    Set<id> accIds = new Set<id>();
    for(Account acc: {
    List<contact> lstCon = [SELECT id,name,Accountid FROM Contact WHERE Accountid IN:accIds];
    for(Account a:
        a.NumberOfContacts__c = lstCon.size();
        system.debug('===no of Contacts====>'+a.NumberOfContacts__c);

Please Select mine is Best Answer If you Can fell.
Suraj Tripathi 47Suraj Tripathi 47
Hi Harish,

"Try below Code."
trigger CountContacts on Account (before update)
-----apex class
public class CountContact{
         public static void countCon(List<Account> accList){
          List<contact> con = [SELECT id,name,Accountid FROM Contact WHERE Accountid IN:accList];
          for(Account acc:accList){
           system.debug('no of Contacts--->'+acc.NumberOfContacts__c);

If you find your Solution then mark this as the best answer. 

Thank you!

Suraj Tripathi