You need to sign in to do that
Don't have an account?
Anil Ingle
How to find "Ultimate Parent" or "Top Level Account" in Account hierarchy?
Our organizations with work multi-level hierarchies of Account.
I was wondering if anyone knows how one can create a script Or SOQL to find out the "Ultimate Parent" and store the result in a field.
Thanks
I was wondering if anyone knows how one can create a script Or SOQL to find out the "Ultimate Parent" and store the result in a field.
Thanks
Try using this utility method which returns ultimate parent account for any given account id
Regards
Lokesh
All Answers
How many level you may have ? Where you want this to implement in trigger or in class ?
Try using this utility method which returns ultimate parent account for any given account id
Regards
Lokesh
===========================================================
public static Map<Id,Id> getTopMostParent(List<Id> AccountIds){
Map<Id,Id> accountToParentAccMap_current = new Map<Id,Id>();
for(Account acc : [select parent.id, parent.parent.id, parent.parent.parent.id, parent.parent.parent.parent.id,parent.parent.parent.parent.parent.Id from Account where id in :AccountIds]){
if(acc.parent.parent.parent.parent.parent.Id != null){ //check for 5th parent
//add accid to list for recursion
accountToParentAccMap_current.put(acc.id,getTopMostParent(new List<Id>{acc.parent.parent.parent.parent.parent.Id}).values()[0]);
}else if(acc.parent.parent.parent.parent.id != null){ //check for 4th parent
accountToParentAccMap_current.put(acc.id,acc.parent.parent.parent.parent.id);
}else if(acc.parent.parent.parent.id != null){ //check for 3rd parent
accountToParentAccMap_current.put(acc.id,acc.parent.parent.parent.id);
}else if(acc.parent.parent.id != null){ //check for 2nd parent
accountToParentAccMap_current.put(acc.id,acc.parent.parent.id);
}else if(acc.parent.id != null){ //check for 1st parent
accountToParentAccMap_current.put(acc.id,acc.parent.id);
}else{ // no parent account
accountToParentAccMap_current.put(acc.id,acc.id); // put the same account id
}
}
return accountToParentAccMap_current;
}