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
Vikram Singh 157Vikram Singh 157 

HI ! Associated contacts not shown with the below triggers..

trigger Ass_cts on Contact (after insert, after undelete) {

set<id> acid = new set<id>();

if (trigger.isinsert||trigger.isundelete){

for (contact opp : trigger.new){

acid.add(opp.accountid);
}
   list<account> acc = [select id, Number_of_contacts__c from account where id in : acid];
   list<contact> con = [select id from contact where accountid in :acid];
   
   for(account a : acc){
   
   a.Number_of_contacts__c = con.size();
      }
     Update acc;
    }
    }
Best Answer chosen by Vikram Singh 157
Shamsi 110Shamsi 110
trigger Ass_cts on Contact (after insert, after undelete) {

set<id> acid = new set<id>();
List<Account> updateAccount = new List<Account>();
if (trigger.isinsert||trigger.isundelete){

for (contact opp : trigger.new){

acid.add(opp.accountid);
}
   Integer contactCOunts = [Select Count() from contact where accountid : acid] 
   
   for(Account acc: acid){
        acc.Number_of_contacts__c = contactCOunts;
        updateAccount.add(acc);
      }
     Update updateAccount;
    }
  }


Hope this helps you out.

Mark it as best.

Thanks,
Shamsi. 

All Answers

Shamsi 110Shamsi 110
trigger Ass_cts on Contact (after insert, after undelete) {

set<id> acid = new set<id>();
List<Account> updateAccount = new List<Account>();
if (trigger.isinsert||trigger.isundelete){

for (contact opp : trigger.new){

acid.add(opp.accountid);
}
   Integer contactCOunts = [Select Count() from contact where accountid : acid] 
   
   for(Account acc: acid){
        acc.Number_of_contacts__c = contactCOunts;
        updateAccount.add(acc);
      }
     Update updateAccount;
    }
  }


Hope this helps you out.

Mark it as best.

Thanks,
Shamsi. 
This was selected as the best answer
Amit Chaudhary 8Amit Chaudhary 8
Try to update your code like below
trigger Ass_cts on Contact (after insert, after undelete) {

	set<id> acid = new set<id>();
	if (trigger.isinsert||trigger.isundelete)
	{
		for (contact opp : trigger.new){
			acid.add(opp.accountid);
		}
		list<account> acc = [select id, Number_of_contacts__c,(select id from contacts) from account where id in : acid];

		for(account a : acc)
		{
			List<Contact> lstContact = a.contacts;
			a.Number_of_contacts__c = lstContact.size();
		}
		Update acc;
	}
}

Let us know if this will help you
Amit Chaudhary 8Amit Chaudhary 8
Hi Vikram,

you will not get perfect count from "Shamsi 110" code if you will update multiple record by data loader because if you will update 2 record together then you will get 2 account Id in "acid". Below query will return count of both account
Integer contactCOunts = [Select Count() from contact where accountid : acid]

not for individual account contact count.