Salesforce has introduced new tag called lightning:treegrid which can be used to display tree structure in tabular form. Lightning:tree can be used to display the hierarchy but if you want to display additional information then lightning:treegrid becomes useful.
If you want to lean how to use lightning:tree tag to display hierarchy for any record then refer below URL:
Lightning Tree : Generic Lightning Component to Display Hierarchy for any sObject
If you have to display account hierarchy along with another fields information as displayed in below image, then use treegrid.
Below is complete code to display account hierarchy. Just pass account record Id and lightning component will display complete hierarchy.
Hope this help!!!
If you want to lean how to use lightning:tree tag to display hierarchy for any record then refer below URL:
Lightning Tree : Generic Lightning Component to Display Hierarchy for any sObject
If you have to display account hierarchy along with another fields information as displayed in below image, then use treegrid.
Below is complete code to display account hierarchy. Just pass account record Id and lightning component will display complete hierarchy.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<aura:application extends="force:slds"> | |
<c:SK_AccountTreeGridCmp ltngcurrentRecId="0010K00001qo2mrQAA"/> | |
</aura:application> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<aura:component controller="SK_AccountTreeGridCmpController"> | |
<aura:attribute name="ltngcurrentRecId" type="String" /> | |
<aura:attribute name="gridColumns" type="list" /> | |
<aura:attribute name="gridData" type="Object" /> | |
<aura:attribute name="gridExpandedRows" type="List" access="PRIVATE" /> | |
<aura:handler name="init" value="{!this}" action="{!c.doInit}" /> | |
<lightning:treeGrid columns="{! v.gridColumns }" | |
data="{! v.gridData }" | |
keyField="name" | |
expandedRows="{! v.gridExpandedRows}" | |
aura:id="mytree" /> | |
</aura:component> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SK_AccountTreeGridCmpController { | |
@AuraEnabled | |
public static List<Account> findHierarchyData(string recId){ | |
List<Account> accList = new List<Account>(); | |
string queryString = 'select id,name,type,industry,parentId from Account '; | |
//Section to get all child account details from ultimate parent starts------------------------- | |
List<String> currentParent = new List<String>{}; | |
Integer level = 0; | |
Boolean endOfStructure = false; | |
//method to find ultimate parent of account | |
string topMostparent = GetUltimateParentId(recId ); | |
system.debug('*******topMostparent:'+topMostparent); | |
currentParent.add(topMostparent); | |
system.debug('**********topMostparent:'+ currentParent); | |
//Loop though all children | |
string finalQueryString = ''; | |
List<Account> queryOutput = new List<Account> (); | |
while ( !endOfStructure ){ | |
if( level == 0 ){ | |
finalQueryString = queryString + ' where id IN : CurrentParent ORDER BY ParentId Limit 1000'; | |
} | |
else { | |
finalQueryString = queryString + ' where ParentID IN : CurrentParent ORDER BY ParentId Limit 1000'; | |
} | |
system.debug('********finalQueryString:'+finalQueryString); | |
if(finalQueryString != null && finalQueryString !=''){ | |
try{ | |
if(Limits.getLimitQueries()-Limits.getQueries()>0){ | |
queryOutput = database.query(finalQueryString); | |
system.debug('***hierarchy level:'+level); | |
}else{ | |
system.debug('****endOfStructure is true as SOQL limit reaches:'); | |
endOfStructure = true; | |
} | |
}catch(exception ex){ | |
endOfStructure = true; | |
} | |
} | |
system.debug('**queryOutput size:'+queryOutput); | |
if( queryOutput.size() == 0 ){ | |
endOfStructure = true; | |
} | |
else{ | |
currentParent.clear(); | |
//iterating through query output | |
for ( Integer i = 0 ; i < queryOutput.size(); i++ ){ | |
currentParent.add(queryOutput[i].Id); | |
accList.add(queryOutput[i]); | |
} | |
} | |
level++; | |
} | |
system.debug('**********accList:'+accList); | |
return accList; | |
} | |
// Find the tom most element in Heirarchy | |
// @return objId | |
public static String GetUltimateParentId( string recId ){ | |
Boolean top = false; | |
while ( !top ) { | |
string queryString = 'select id ,name, ParentId from Account where Id =:recId LIMIT 1'; | |
Account acc = database.query(queryString); | |
if ( acc.parentId != null ) { | |
recId = acc.parentId; | |
}else { | |
top = true; | |
} | |
} | |
return recId ; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
({ | |
doInit: function (component, event, helper) { | |
console.log('doInit of component called'); | |
var columns = [ | |
{ | |
type: 'url', | |
fieldName: 'AccountURL', | |
label: 'Account Name', | |
typeAttributes: { | |
label: { fieldName: 'accountName' } | |
} | |
}, | |
{ | |
type: 'text', | |
fieldName: 'Industry', | |
label: 'Industry' | |
}, | |
{ | |
type: 'type', | |
fieldName: 'Type', | |
label: 'Type' | |
} | |
]; | |
component.set('v.gridColumns', columns); | |
var trecid = component.get('v.ltngcurrentRecId'); | |
//var tsObjectName= component.get('v.ltngSobjectname'); | |
//var tparentFieldAPIname= component.get('v.ltngParentFieldAPIName'); | |
//var tlabelFieldAPIName= component.get('v.ltngLabelFieldAPIName'); | |
if(trecid){ | |
helper.callToServer( | |
component, | |
"c.findHierarchyData", | |
function(response) { | |
var expandedRows = []; | |
var apexResponse = response; | |
var roles = {}; | |
console.log('*******apexResponse:'+JSON.stringify(apexResponse)); | |
var results = apexResponse; | |
roles[undefined] = { Name: "Root", _children: [] }; | |
apexResponse.forEach(function(v) { | |
expandedRows.push(v.Id); | |
roles[v.Id] = { | |
accountName: v.Name , | |
name: v.Id, | |
Type:v.Type, | |
Industry:v.Industry, | |
AccountURL:'/'+v.Id, | |
_children: [] }; | |
}); | |
apexResponse.forEach(function(v) { | |
roles[v.ParentId]._children.push(roles[v.Id]); | |
}); | |
component.set("v.gridData", roles[undefined]._children); | |
console.log('*******treegrid data:'+JSON.stringify(roles[undefined]._children)); | |
component.set('v.gridExpandedRows', expandedRows); | |
}, | |
{ | |
recId: component.get('v.ltngcurrentRecId') | |
} | |
); | |
} | |
} | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
({ | |
callToServer : function(component, method, callback, params) { | |
console.log('Calling helper callToServer function'); | |
var action = component.get(method); | |
if(params){ | |
action.setParams(params); | |
} | |
console.log(JSON.stringify(params)); | |
action.setCallback(this, function(response) { | |
var state = response.getState(); | |
if (state === "SUCCESS") { | |
//alert('Processed successfully at server'); | |
callback.call(this,response.getReturnValue()); | |
}else if(state === "ERROR"){ | |
alert('Problem with connection. Please try again.'); | |
} | |
}); | |
$A.enqueueAction(action); | |
} | |
}) |
Hope this help!!!
useful post.
ReplyDeleteyou people are really great ,i am getting the ERROR in the following lines.please help.
ReplyDeletecomponent.set("v.gridData", roles[undefined]._children);
console.log('*******treegrid data:'+JSON.stringify(roles[undefined]._children));
you people are really great ,i am getting the ERROR in the following lines.please help.
ReplyDeletecomponent.set("v.gridData", roles[undefined]._children);
console.log('*******treegrid data:'+JSON.stringify(roles[undefined]._children));
This page has an error. You might just need to refresh it.
ReplyDeleteError in $A.getCallback() [Cannot read property 'config' of undefined]
Callback failed: apex://SK_AccountTreeGridCmpController/ACTION$findHierarchyData
Failing descriptor: {c:SK_AccountTreeGridCmp}
Hi,
DeleteCan you please code to call this component. I just wanted to know what all parameters you are passing to this component.
Thanks
I call the component by below code:
DeleteThank you so much !!!
ReplyDeleteCan you please help load asynchronous on tree grid.
ReplyDeleteThis works as a pro Awesome Site.
ReplyDeleteCant see the code any longer?!
ReplyDeletei am not able to see the code , please review the page ?
ReplyDeleteHi, Is there a way to retain the checkbox of child rows when the parent row is expanded and collapsed? Sample code should be really helpful. I am facing one issue with the tree grid when i expand the parent row and then i checked few child rows and then collapsed and re expanded the parent row. The check boxes on child rows are no longer checked.
ReplyDeleteCan we add icons infront of Account Name to define what type of Account this is?
ReplyDeleteI am not able to view code, please recheck...
ReplyDeleteHello , thank you for the code sample, I need a modification in this but not able to do that, plz help in this if possible, I want to remove the arrow mark before the code if there is no child for that record. How to do that
DeleteWow. There's some magic in there I do not understand!
ReplyDeleteSo you return a list of accounts then, somehow, created the tree structure.
How does this section of code work?
----------------------
var roles = {};
console.log('*******apexResponse:'+JSON.stringify(apexResponse));
var results = apexResponse;
roles[undefined] = { Name: "Root", _children: [] };
apexResponse.forEach(function(v) {
expandedRows.push(v.Id);
roles[v.Id] = {
accountName: v.Name ,
name: v.Id,
Type:v.Type,
Industry:v.Industry,
AccountURL:'/'+v.Id,
_children: [] };
});
apexResponse.forEach(function(v) {
roles[v.ParentId]._children.push(roles[v.Id]);
});
component.set("v.gridData", roles[undefined]._children);
---------------------
what is the [undefined] syntax?
OK. I get it now. The accountID is usually the index but you create a special, easily identifiable, index using 'undefined' and this is the root node of everything else.
DeleteI love it. Thank you so much for the blog.
In fact, it does the whole accounts hierarchy with a simple apex method:
ReplyDelete@AuraEnabled
public static List fetchAllAccounts (){
List accList = new List();
accList = [SELECT Id, ParentID, Name FROM Account WHERE IsPersonAccount = false ORDER BY Name];
return accList;
}
Amazing.
Homeowners who try to tackle the chore of removing a tree by themselves often find that they are rapidly overwhelmed by the task. tree removal
ReplyDeleteWhether you are looking to have an entire tree removed or one or two stumps that need grounding down, you will certainly appreciate the quality services offered by the tree surgeon. tree surgeon worcester
ReplyDeleteYou can also search on the internet and find websites where you can avail surgeon of tree service. tree surgeon luton
ReplyDelete