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.
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!!
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?
ReplyDeleteHello Madam and Sir
ReplyDeleteYour 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
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/
ReplyDeleteGreat post ! Dot net development services
ReplyDeleteArtattackk is a well-knowned Website Designing Company In Delhi having 11+years of experience.
ReplyDeleteLenovo Service Center in Mumbai
ReplyDelete