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
Dean BarnesDean Barnes 

Looping through accounts and then associated contacts

I am trying to create a bit of Apex code that will loop through accounts, find the associated contacts and then loop through the contacts to get their names. I'm not having much luck, but has anyone done this before and knows how to do it?

Best Answer chosen by Admin (Salesforce Developers) 
Dean BarnesDean Barnes

Apologies for not providing any apex of visualforce code, but I only had a for loop in the former and the second just had a button. I didn't think this provided much information. For anyone trying to solve this problem in the future, the following code did what I needed:

public void Loop()
{
    // Loop through all the accounts, each time getting the information on contacts
    for (Account account : [SELECT Name, (SELECT Name FROM Contacts) FROM Account])
    {
        // Add the account name to the message area
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING, 'Account: ' + account.name));
    
        // Loop through all the contacts for the account
        for (Contact contact : account.Contacts)
        {
            // Add the contact name to the message area
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING, '- Contact: ' + contact.name));
        }
    }
}

 

All Answers

Doze2KatzsDoze2Katzs

 

You haven't given much information about where you will be looping through the Accounts, such as a VisualForce page or maybe you are looping in a trigger.

 

First, you should read some of the documentation on Developer force.  A good starting point is: http://wiki.developerforce.com/index.php/Documentation#Apex_and_Visualforce.

 

I understand everyone learns differently, but I feel if you try some code first and then post it, you might get more help.  If you want a developer to put some effort into helping you, then you should put some effort also!  Just my 2 cents!:smileyhappy:  Anyway, enough preaching!!!!

 

Below is some sample code you can accomplish your task with two custom variables.

 

The first is 'acct' - that will hold one specific acct.  The second is a list of contacts 'cts', that will hold the related contacts for the specific account in 'acct'

 

 

    public Account acct { get; private set;}
    public List<Contact> cts { get; private set; }
    

    void getAcctContacts(id id) {
        acct = [SELECT Id, Name,
        (SELECT Id, Name FROM Contacts) FROM Account
        where id = :id limit 1];
        cts =acct.Contacts;
     }

getAcctContacts('001E0000002XxXx');
system.debug('acct.name= ' + acct.name);
system.debug('cts.size = ' + cts.size());
for (Contact ct : cts) {
    system.debug('ct.name = ' + ct.name);
}

 

You can run this in the System Console to see the results. Before running, you must get a valid Account ID from your organization and replace it on the line that calls the method.

 

 

 

getAcctContacts('001E0000002XxXx');

 

 

The getAcctContacts method works on one Account ID at a time.  So you can place it into a For loop and traverse a list of accounts or you can change the parameter of the method to accept a Set of Ids.  Either way should work.  I just retrieved the ID and Name field for both the Account and Contact object, but you can retrieve more fields as needed. 

 

Hope this helps you!

 

 

 

Dean BarnesDean Barnes

Apologies for not providing any apex of visualforce code, but I only had a for loop in the former and the second just had a button. I didn't think this provided much information. For anyone trying to solve this problem in the future, the following code did what I needed:

public void Loop()
{
    // Loop through all the accounts, each time getting the information on contacts
    for (Account account : [SELECT Name, (SELECT Name FROM Contacts) FROM Account])
    {
        // Add the account name to the message area
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING, 'Account: ' + account.name));
    
        // Loop through all the contacts for the account
        for (Contact contact : account.Contacts)
        {
            // Add the contact name to the message area
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.WARNING, '- Contact: ' + contact.name));
        }
    }
}

 

This was selected as the best answer