• Craig Maxwell 14
  • NEWBIE
  • 0 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies
Hi All,

I am having some trouble getting this code snippet to work. I am relatively new to Apex and DML/SOQL so it could be something simple. My goal is, given a list of accounts, determine the number of contacts belonging to each account, and then update a field called Number_of_Contacts__c with that value. Here's what I came up with:
public class AccountProcessor {

    public static void countContacts(List<ID> recordIds){  //take a list of recordids
        
        List<Account> accountlist = 
        [Select name FROM Account WHERE ID IN :recordIDs];  //get a list of the corresponding accounts
        
        for(Account tempaccount: accountlist){  //for each account in this list...
            
            Integer contactCount = 0;
            contactCount = 
            [SELECT Count() from CONTACT WHERE contact.account.ID = :tempaccount.ID];
            //count the number of contacts associate with each account

            tempaccount.number_of_contacts__c = contactCount;
            update tempaccount;
            
        }
    }
}
I am trying to run this code using the following anonymous execution:
AccountProcessor.countContacts(001f400000KfIMbAAN);
I'm not sure if the AccountID should be in quotes are not, but it doesn't work either way. I keep getting the following error:

Line: 1, Column 31 Unexpected token '('.

Any ideas where I'm going wrong? Also, I know my code is violating several "Best Practices" but I'm just trying to figure things out at the moment. Thanks!