+ Start a Discussion
MaheemSamMaheemSam 

Parent and Child Hierarchy in code

Hi, 

   Need experts suggestion on this new requirement. I have a requirement in Account and Contact hierarchies 
  
   Example : 

   Account A  = 10 Contacts  = No Parent
   Account B  = 5 Contacts  = Account A is Parent 
   Account C  = 20 Contacts = Account B is Parent 
   Account D = 3 Contacts = Account B is Parent 
   Acconut E = 2 Contacts = Account C is Parent 

Now my requirement here is if Account B -- Contact is checked I need a result of Account B,C and D list of contacts Please suggest me how to achive this hierachy in code

Similarly If Account C -- contact is checked/searched I need a result of Account C and E list of contacts 

Please let me know if my example is not clear I can explain in clear again need salesforce expters to suggest me on this requirement.  

Thanks
Sudhir 
LBKLBK
Hi Sudhir,

Try the following piece of code to fetch all the contacts of an Account and it's children.
 
String sAccountId = '00128000002MJbS';
List<Contact> lstContacts = new List<Contact>([SELECT ID, Name, Account.Name FROM Contact WHERE AccountId IN(SELECT ID FROM Account WHERE ID =: sAccountId OR ParentId =: sAccountId)]);
System.debug(lstContacts);
I have hardcoded the value for sAccountId, which you can replace as you need in your logic.

Let me know how it goes.
 
MaheemSamMaheemSam
Thanks for you reply but this logic wont work it just shows String sAccountId = '00128000002MJbS';  contacts not even the parent contacts. 

In your code your assign sAccountId to Id and ParentId 

Example: from above thread in my first post 

If Account B is passed in SOQL Account A is parent and Account B has Account C and D as child

   All Account A,B,C,D  list of contacts should be displayed. Hope you undrestand the requirement. 

Thanks
Sudhir

 
 
LBKLBK
Your Original requirement says that you want the contacts of the Account and it's children. It was not talking about the Account's parent.

Here is the updated code.
String sAccountId = '00128000002MJbS';
List<Account> lstAccounts = new List<Account>([SELECT ID, ParentId FROM Account WHERE ID =: sAccountId OR ParentId =: sAccountId]);
List<Id> lstAccountIds = new List<Id>();
for(Account objAccount : lstAccounts){
	lstAccountIds.add(objAccount.Id);
	if(objAccount.ParentId != null){
		lstAccountIds.add(objAccount.ParentId);
	}
}
List<Contact> lstContacts = new List<Contact>([SELECT ID, Name, Account.Name FROM Contact WHERE AccountId =: lstAccountIds]);
System.debug(lstContacts);
As I have mentioned in the previous response, 00128000002MJbS is my Account B (Hard coded value). You have to replace it in your code with either a dynamic variable or a value from query string, depends on your logic.