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
PlatFormCloudPlatFormCloud 

Trigger Doubt in finding the number of Contacts associated with Account

Hi saleForce Experts,
I have a trigger on Contact. I hahe functionality to update the number of contacts in Account. I have a field in Account as "No_of_Associated_Contacts__c". Below is the trigger. 
Please help me Where I am doing wrong?

trigger NumberOfContacts on Contact (after insert, after undelete) {
  Set<Id> accountIds = new Set<Id>();
    for(Contact c:trigger.new){
         accountIds.add(c.Id);
        }
    List<Account> accLst = [SELECT ID, No_of_Associated_Contacts__c FROM Account where Id IN:accountIds];
    List<Contact> con = [SELECT Id FROM Contact WHERE Accountid IN:accountIds];
    
  for(Account a: accLst){
      a.No_of_Associated_Contacts__c = con.size();
      System.debug('Number Of Associated Contacts' + a.No_of_Associated_Contacts__c);
      System.debug('Number Contact Size' + con.size());

      
  }
   update accLst;
}
Best Answer chosen by PlatFormCloud
Amit Chaudhary 8Amit Chaudhary 8
I have updated the below in trigger
1) Added update and Delete event
2) Added trigger.old for Delete event
3) Added Null Check

Please try below code.
trigger NumberOfContacts on Contact ( after delete, after insert, after update ) 
{
	Set<Id> accountIds = new Set<Id>();
	if(Trigger.isDelete)
	{
		for(Contact c : trigger.old)
		{
			accountIds.add(c.AccountId);
		}
	}
	else
	{
		for(Contact c : trigger.new)
		{
			accountIds.add(c.AccountId);
		}
	}

	if(accountIds.size() > 0 )
	{	
		list<account> accLst = new list<account>();	
		for(Account objAcc: [select id,No_of_Associated_Contacts__c,(select id from contacts) from account where id In : accountIds])
		{
			objAcc.No_of_Associated_Contacts__c = objAcc.contacts.size();
			accLst.add(objAcc);
		}
	
		if(accLst.size() > 0 )
		{
			update accLst;
		}	
	}	
}

Please let us know if this will help you

Thanks
Amit Chaudhary
 

All Answers

PavanKPavanK
Please try below code and mark if it resolved issue
 
PavanKPavanK
trigger NumberOfContacts on Contact (after insert, after undelete)
{
  Set<Id> accountIds = new Set<Id>();
  list<account> accLst = new list<account>();
    for(Contact c:trigger.new)
    {
         accountIds.add(c.AccountId);
    }
  for(Account objAcc: [select id,(select id from contacts) from account where id In : accountIds])
{
    objAcc.No_of_Associated_Contacts__c = objAcc.contacts.size();
     accLst.add(objAcc);
}
   update accLst;
}
PlatFormCloudPlatFormCloud
Thanks PavanK. The code is working prefectly fine.
I do have 2 quesries here:

1. This type od writing 'SELECT' query is not against the best practises, right? (Just asking to clear my doubt)
for(Account objAcc: [select id,(select id from contacts) from account where id In : accountIds])

2. We have not queried 'No_of_Associated_Contacts__c' in the SOQL query, still the code is working fine, How, Can you please explain.

Thanks!
Amit Chaudhary 8Amit Chaudhary 8
I have updated the below in trigger
1) Added update and Delete event
2) Added trigger.old for Delete event
3) Added Null Check

Please try below code.
trigger NumberOfContacts on Contact ( after delete, after insert, after update ) 
{
	Set<Id> accountIds = new Set<Id>();
	if(Trigger.isDelete)
	{
		for(Contact c : trigger.old)
		{
			accountIds.add(c.AccountId);
		}
	}
	else
	{
		for(Contact c : trigger.new)
		{
			accountIds.add(c.AccountId);
		}
	}

	if(accountIds.size() > 0 )
	{	
		list<account> accLst = new list<account>();	
		for(Account objAcc: [select id,No_of_Associated_Contacts__c,(select id from contacts) from account where id In : accountIds])
		{
			objAcc.No_of_Associated_Contacts__c = objAcc.contacts.size();
			accLst.add(objAcc);
		}
	
		if(accLst.size() > 0 )
		{
			update accLst;
		}	
	}	
}

Please let us know if this will help you

Thanks
Amit Chaudhary
 
This was selected as the best answer
PlatFormCloudPlatFormCloud
*Hi Amit,
Thanks for making the code more clean. One question out-of-trigger- How you present the eclipse view in this forum(with Line number, colour coding etc). Please let me know, because this view presents better readability and help every developer to understand the code fast and easily. 
 
Amit Chaudhary 8Amit Chaudhary 8

User-added image
NOTE: When adding code please use the "Add a code sample" button (icon <>) to increase readability and make it easier to reference.

Let us know if this will help you
PavanKPavanK
Answer to your questions

1. This type od writing 'SELECT' query is not against the best practises, right? (Just asking to clear my doubt)
for(Account objAcc: [select id,(select id from contacts) from account where id In : accountIds])
I don't think its bad practice. Instead you can use aggregate query which will be effective.

2. We have not queried 'No_of_Associated_Contacts__c' in the SOQL query, still the code is working fine, How, Can you please explain.
Because you are not using this field and only populate this field. If you use field without querying to get data you may face issue.

For example in Visualforce page- without querying you are trying to display field on VF page then it will give you error.

Please mark this as best anser if I helped in your query.

Thanks
PlatFormCloudPlatFormCloud
Hi PavanK and Amit,
Appreciate your technical understanding. Can you please help in coding bt the use of Aggregate Query? 

Thanks!