Hi All,
I am writing this post because 2-3 clients came up with this same requirement, to show all the contacts of child Accounts in their parent Account.
I am explaining this requirement in detail with an example:-
Suppose there is Account "A" who is parent of Account "B".
now account "B" has 2 contacts "B1" and "B2".
client want to see this "B1" & "B2" contacts in parent account "A", so that he can easily know which contact associated with which account on same page easily.
And this is not only limited to 2 level it is goes to up to 100 level (we can't Query more then 100 in one context because of Governor limit).
I solved this problem by creating a VF page and add it to Detail page of Account, So now user can able to see all the contacts associated with the Account and their child Accounts in a same page.
Here the code:-
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<apex:page standardController="Account" extensions="ChildAccountsContactsController"> | |
<apex:pageblock> | |
<apex:pageBlockSection title="All Contacs including child Accounts" columns="1"> | |
<apex:pageBlockTable value="{!allContactNames}" var="con"> | |
<apex:column value="{!con.Name}" headerValue="Contact Name"/> | |
<apex:column value="{!con.Account.Name}" headerValue="Contact's Account Name"/> | |
<apex:column value="{!con.Account.Parent.Name}" headerValue="Contact's Parent Account Name"/> | |
</apex:pageBlockTable> | |
</apex:pageBlockSection> | |
</apex:pageblock> | |
</apex:page> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ChildAccountsContactsController{ | |
public List<Contact> allContactNames{get;set;} | |
public ChildAccountsContactsController.ChildAccountsContactsController(ApexPages.StandardController controller){ | |
Id accId = controller.getId(); | |
Set<Id> allChildAccount = getAllChildAccountIds(accId); | |
allContactNames = new List<Contact>(); | |
allContactNames = [Select Id, Name, Account.Name, Account.Parent.Name from Contact where AccountId in :allChildAccount]; | |
} | |
private Set<Id> getAllChildAccountIds(Id parentAccountId){ | |
Set<Id> AccountIdSet = new Set<Id>(); | |
AccountIdSet.add(parentAccountId); | |
Boolean check=true; | |
do | |
{ | |
List<Account> accIds = [select Id from Account where ParentId in:AccountIdSet And Id not in:AccountIdSet]; | |
if(accIds != null && accIds.size() > 0){ | |
for(Integer i=0; i<accIds.size(); i++){ | |
AccountIdSet.add(accIds[i].Id); | |
} | |
} | |
else | |
check = false; | |
}while(check); | |
return AccountIdSet; | |
} | |
} |
Screen Shots:-
Happy Coding...:)
Thanks
Anurag Jain