Wednesday, October 12, 2022

How to get list of all accounts present in account hierarchy in Salesforce

 As a developer, we always get requirement to display records in their hierarchy (Account Hierarchy, Case Hierarchy etc). Using SOQL queries, its really tough to get all accounts in hierarchy as we have to fire multiple SOQL queries to get ultimate parent record id if we are on a record which is 3 or 4 level down in hierarchy. 

Instead of achieving everything using SOQL, we can create formula field "Ultimate Account Id" in account object which will store ultimate account record id on all account records present in account hierarchy. As formula field allows you to refer upto 10 parent, we can easily get list of all account in account hierarchy upto 10 levels.


Below is formula for Ultimate Account Id.


Now if you know account record id, just get Ultimate Account Id field value and then query all accounts which have this ultimate account Id.

Below is static method which can be used to get list of all account present in account hierarchy.

public static list<Account> findAllHierarchyAccounts(string recordId){
list<Account> allAccountList=new List<Account>();
string ultimateAccountId;
for(Account acc:[select Ultimate_Account_Id__c from Account where Id=:recordId]){
ultimateAccountId=acc.Ultimate_Account_Id__c;
}
if(string.isNotBlank(ultimateAccountId)){
for(Account acc:[select id,Name,ParentId
from Account where Ultimate_Account_Id__c=:ultimateAccountId]){
allAccountList.add(acc);
}
}
system.debug('***allAccountList size:'+allAccountList);
return allAccountList;
}

Hope this will help!!


4 comments:

  1. Thanks for the information shared. Keep updating blogs regularly. If you have time visit
    Grid False Ceiling in Coimbatore

    ReplyDelete
  2. Hi! Great writeup - super helpful. I'm a salesforce novice on the back end but if i wanted to pull the Ultimate Parent account name could i swap the Parent.Id fields with Parent.Name?

    ReplyDelete
  3. Hello Madam and Sir
    Your serious and honest loan offer
    The loan varies from 5,000 to 1,500,000 euros and the documents are available to us, please contact me by email: financialserviceoffer876@gmail.com whats-App +918929509036

    ReplyDelete
  4. Hello, This blog is very informative for every one, It's a Great think to help everyone thanks. Visit our website and find Great products in very cheap price https://alphatrade-ltd.com/

    ReplyDelete