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
VisithraVisithra 

Help to get this future method asynchronous apex

Create a future method to calculate total number of contacts under each account and update it in the account custom field names as number of contacts field, implement this using future method.
 
HarshHarsh (Salesforce Developers) 
Hi Visithra,
You can use the following code to achieve your requirement.
public class AccountProcessor
{
  @future
  public static void countContacts(Set<id> setId) 
  {
      List<Account> lstAccount = [select id,Number_of_Contacts__c , (select id from contacts ) from account where id in :setId ];
      for( Account acc : lstAccount )
      {
          List<Contact> lstCont = acc.contacts ;
          
          acc.Number_of_Contacts__c = lstCont.size();
      }
      update lstAccount;
  }
}

You can refer to the below link as it has the same question on the forum.
https://developer.salesforce.com/forums/?id=906F0000000D8hwIAC

Please mark it as Best Answer if the above information was helpful.

Thanks.
Arun Kumar 1141Arun Kumar 1141

Hi Visithra,

Please refer to the below code :

To define a future method, simply annotate it with the future annotation, as follows.

 

public class CountContactsInAccounts
{
  @future
  public static void demo(Set<id> ids) 
  { 
   List<Account> accList = [SELECT id,Number_of_Contacts__c , (SELECT id FROM Contacts ) FROM Account WHERE id in :ids ] ;
      for( Account acc :  accList)
      {   
          acc.Number_of_Contacts__c =  acc.contacts.size();
      }
      update accList;
  }
}

Please mark it as best answer if it helps.

Thanks,