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
Kiran PandiyanKiran Pandiyan 

Why the number of contacts value is not populated in the field ?

public class AccountProcessor {
	@future
    public static void countContacts(set<Id> recIds){
        List<Account> accs = [Select Id, Name from Account Where Id IN :recIds];
        
        for(Account ac :accs){
            ac.Number_of_Contacts__c=[SELECT COUNT() FROM Contact WHERE Account.Id=:ac.Id];
        }
        
       update accs; 
    }
}

I'm try 'Use Future methods' challenge in Asynchronous Apex module. After saving the code and running it in anonymous window, the value is not populated , how can I solve the issue
ManidManid
Hai ! Kiran i think its          accountid  not account.id
Kiran PandiyanKiran Pandiyan
@Manid 
No it is still not working
VamsiVamsi
public class AccountProcessor {
	@future
    public static void countContacts(set<Id> recIds){
        List<Account> accs = [Select Id, Name from Account Where Id IN :recIds];
        
List<Account> Accupdate = new List<Account>();
        for(Account ac :accs){
            ac.Number_of_Contacts__c=[SELECT COUNT() FROM Contact WHERE AccountId=:ac.Id];
Accupdate.add(ac);

        }
        
if(Accupdate.size()>0)
{
       update Accupdate ; 
 }
   }
}
Hope the above code helps ...!!!

Please mark as best answer if the above helps ...!!!
Kiran PandiyanKiran Pandiyan
@Vamsi No this is also not working Vamsi.
By the way, Doesn't it throw too many SOQL error as the code will create a new SOQL query for every iterations of for loop ?
VamsiVamsi
Hi Kiran,

Please try the below code and it should work as it works for me.
 
public class AccountProcessor 
{
	@future
    public static void countContacts(set<Id> recIds)
	{
        List<Account> accs = [Select Id, Name,Number_of_Contacts__c from Account Where Id IN :recIds];
        Map<Id,Integer> Consize = new Map<Id,Integer>();  
        for(AggregateResult ar: [Select Count(Id) ContactCount, AccountId from Contact where AccountId IN: accs GROUP BY AccountId])
		{
		  Consize.put((id)ar.get('AccountId'),(Integer)ar.get('ContactCount'));
		}

		List<Account> FinalAccList = new List<Account>();
		for(Account an : accs)
		{
			an.Number_of_Contacts__c = Consize.get(an.id);
			FinalAccList.add(an);
		}
        
		 if(FinalAccList.size()>0)
		 {
		  update FinalAccList;
		 }
    }
}
Also, how are you invoking this future method ? from a trigger? 
 
Kiran PandiyanKiran Pandiyan

@Vamsi From  Anonymous window of Dev Console

No, this code also doesn't work for me. Will there be any interference from other Triggers/Classes/Validation Rule