function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
kamal3883kamal3883 

Dynamic extraction of parent account

Hi,

 

I want to dynamically extract parentid of account. this is like this.

 

suppose we have account hiearchery A--B--C---D--E . now on E i want to populate id of A. but i dont know length of hiearchery. 

 

Can somebody help on this ?

Best Answer chosen by Admin (Salesforce Developers) 
Dhaval PanchalDhaval Panchal

Try this,

 

boolean found = false;
Id currentId = 'fdsafdsaf';//initialize with your current record

while (!found){
	Account a = [select id, parent.Id from account Where Id=:currentId];
	if(a.parentId == null){
		found = true;
		parentId = a.Id;//most parent has parent id = null so this is an root parent
	}
	currentId = a.parent.Id;
}

 

All Answers

Sailappa VigneshSailappa Vignesh

Hi Kamal,

 

You can acheive this by formula field.Create a forumula field in account select text as type and paste the following code in it it will reteive the ID of Account (A)

 

Parent.Parent.Parent.ParentId

 

 

Please mark as right answer if its help!

kamal3883kamal3883

Hi,

 

What if there are six or 10 record in hierarchy. this formula is not dynamic. i am ready to write anything in apex too.

Dhaval PanchalDhaval Panchal

Try this,

 

boolean found = false;
Id currentId = 'fdsafdsaf';//initialize with your current record

while (!found){
	Account a = [select id, parent.Id from account Where Id=:currentId];
	if(a.parentId == null){
		found = true;
		parentId = a.Id;//most parent has parent id = null so this is an root parent
	}
	currentId = a.parent.Id;
}

 

This was selected as the best answer