+ Start a Discussion
Adam DillmanAdam Dillman 

Calculate the number of contacts for a given account record - not working

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!





 
Best Answer chosen by Adam Dillman
Narender Singh(Nads)Narender Singh(Nads)

Hi Adam,
The reason it is not working is because your function is expecting a list of IDs but you are passing just an ID. To achieve that you need to add that ID to a list and then pass it to your function:
Your function call should look something like this:

list<id> IDList= new list<id>();

IDList.add('Put your ID here'); // Remember to put your id within quotes

AccountProcessor.count(IDList);

This should resolve your error.

Let me know if it helps.
Thanks :)

All Answers

Abdul KhatriAbdul Khatri
Simplifying the code
 
List<Account> accountlist  = [Select Id, number_of_contacts__c, (Select Id From Contacts) From Account Where Id IN :recordIDs];  //get a list of the corresponding accounts
for(Account account : accountlist) {
    
    if(account.Contacts == null) continue;
    
    account.number_of_contacts__c = account.Contacts.size();
}

update accountList;

 
Narender Singh(Nads)Narender Singh(Nads)
Hi, 
account[] accountlist  = [Select Id, number_of_contacts__c, (Select Id From Contacts) From Account Where Id IN :recordIDs];  //get a list of the corresponding accounts
account[] UpdateAccList= new account[]{};

for(Account account : accountlist) {
    if(account.Contacts == null) 
    continue;
    
    account.number_of_contacts__c = account.Contacts.size();
    UpdateAccList.add(account);
}

update UpdateAccList;

Let me know if it helps.
Thanks.

Adam DillmanAdam Dillman
@Narender,

Thanks for your suggestions. I tried replacing the body of my method with your code. However, when I try to call the method using
 
AccountProcessor.countContacts(001f400000KfIMbAAN);

I get the error: "Line: 1, Column: 31 Unexpected token '('."

Any ideas?
Gururaj BGururaj B
The function that you have written is expecting the List of id as argument and you are not passing the correct data type. So try this and mark as best asnwer if it resolve your issue.

list<id> Idlst=new list<id>();
Idlst.add('001f400000KfIMbAAN');
AccountProcessor.countContacts(Idlst);
Narender Singh(Nads)Narender Singh(Nads)

Hi Adam,
The reason it is not working is because your function is expecting a list of IDs but you are passing just an ID. To achieve that you need to add that ID to a list and then pass it to your function:
Your function call should look something like this:

list<id> IDList= new list<id>();

IDList.add('Put your ID here'); // Remember to put your id within quotes

AccountProcessor.count(IDList);

This should resolve your error.

Let me know if it helps.
Thanks :)

This was selected as the best answer
Abdul KhatriAbdul Khatri
Arent' you going to call this method on trigger or any button click on a visualforce page. Please make sure the List of Ids you are passing to the method must be Account Ids, otherwise nothing going to work. 

If you are planning to call it from a trigger, here is the one way to call it
 
trigger UpdateAccountContactCount on Contact (after insert, after delete) {
	
    List<Contact> contactList = trigger.isDelete ? trigger.old : trigger.new;
    List<Id> idAccountList = new List<Id>();
    for(Contact contact : contactList) {
		
        if(contact.AccountId == null) continue;
        
        idAccountList.add(contact.AccountId);
    }
    
    if(idAccountList.isEmpty) return;
    
    AccountProcessor.countContacts(idAccountList);
}
 
public class AccountProcessor {

    public static void countContacts(List<ID> recordIds){  //take a list of recordids

        List<Account> accountlist  = [Select Id, number_of_contacts__c, (Select Id From Contacts) From Account Where Id IN :recordIDs];  //get a list of the corresponding accounts
        for(Account account : accountlist) {
            
            if(account.Contacts == null) continue;
            
            account.number_of_contacts__c = account.Contacts.size();
        }
        
        update accountList;        
    }
}
Craig Maxwell 14Craig Maxwell 14
Really simple way to achieve this with clicks not code here, and it's totaly free! How to create a contact count roll up field for Salesforce accounts in 3 simple steps (https://blog.saleshud.com/how-to-create-a-contact-count-roll-up-field-for-salesforce-accounts-in-3-simple-steps" target="_blank)