You need to sign in to do that
Don't have an account?
Dean 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?
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:
All Answers
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'
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.
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!
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: