Winter'18 Salesforce have added a new lightning component called lightning:tree, using this we can display the hierarchy of Salesforce.
In this component is going to be great help to all the devs, when they want achieve the accordion looking hierarchy displaying component. This component support only version
41.0 and above
Here is the working demo
So in this post we have a small component which displays the account hierarchy upto
3 levels, I am not further on achieving the hierarchy of Account using Apex, so I did what I can using just a single SOQL.
Here is the component code
<aura:component controller="LightningTreeApexController" implements="flexipage:availableForRecordHome,force:lightningQuickActionWithoutHeader,force:hasRecordId"> >
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:attribute name="items" type="Object"/>
<aura:attribute name="recordId" type="String"/>
<lightning:tree items="{! v.items }" header="Account Hierarchy" onselect="{!c.handleSelect}"/>
</aura:component>
Here Lightning component Controller code
({
doInit: function (cmp, event, helper) {
helper.apexMethod(cmp);
},
handleSelect: function (cmp, event, helper) {
//return name of selected tree item
var myName = event.getParam('name');
alert("You selected: " + myName);
}
})
Here is the helper code
({
apexMethod : function(cmp) {
var action = cmp.get("c.getAccountHierarchy");
action.setParams({ accountId : cmp.get("v.recordId") });
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
cmp.set( "v.items", response.getReturnValue());
}
});
$A.enqueueAction(action);
}
})
Here is Apex Controller
public class LightningTreeApexController {
@AuraEnabled
public static List<items> getAccountHierarchy(Id accountId) {
//Wrapper instance
List<items> finalWrp = new List<items>();
//Going upto 2 level only as per SOQL limit
for(Account acc : [ Select Id, Name, Type, ParentId, Parent.Name, Parent.Type, Parent.ParentId, Parent.Parent.Name, Parent.Parent.Type From Account Where Id =: accountId]) {
//populating wrapper
List<items> trP1 = new List<items>{new items(acc.Type, acc.Name, false, null)};
List<items> trP2 = new List<items>{new items(acc.Parent.Type, acc.Parent.Name, false, trP1)};
finalWrp.add(new items(acc.Parent.Parent.Type, acc.Parent.Parent.Name, false, trP2));
}
System.debug('finalWrp:::' + finalWrp);
// return wrapper
return finalWrp;
}
}
Here is wrapper class used in Apex controller
public class items {
@AuraEnabled
public string label { get; set; }
@AuraEnabled
public string name { get; set; }
@AuraEnabled
public Boolean expanded { get; set; }
@AuraEnabled
public List<items> items { get; set; }
public items( String name, String label, Boolean expanded, List<items> items) {
this.label = label;
this.name = name;
this.expanded = expanded;
this.items = items;
}
}
Some important
links to learn more about Winter'18 Release
Thanks you