Skip to content

Instantly share code, notes, and snippets.

@brianmfear
Last active January 29, 2020 15:41
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianmfear/0d26e0b9e612a235c7a4b84a86397113 to your computer and use it in GitHub Desktop.
Save brianmfear/0d26e0b9e612a235c7a4b84a86397113 to your computer and use it in GitHub Desktop.
lightning:tree with account hierarchy recursion example
public class AccountData {
@AuraEnabled public static Account[] getRecords() {
return [SELECT Name, ParentId, (SELECT Name FROM Contacts) FROM Account];
}
}
<aura:application controller="AccountData" extends="force:slds">
<aura:attribute name="data" type="List" default="[]" />
<aura:handler name="init" value="{!this}" action="{!c.init}" />
<lightning:tree header="Accounts" items="{!v.data}" />
</aura:application>
({
init: function(component, event, helper) {
var action = component.get("c.getRecords");
action.setCallback(this, result => helper.parse(component, result));
$A.enqueueAction(action);
}
})
({
parse: function(component, result) {
var accounts = result.getReturnValue(),
parents = { undefined: { items: [] }};
accounts.forEach(account => parents[account.Id] = { items: [], name: account.Id, label: "Account: "+account.Name, expanded: false});
accounts.forEach(account => { if(account.Contacts) { account.Contacts.forEach(contact => parents[account.Id].items.push({items: [], name: contact.Id, label: "Contact: "+contact.Name, expanded: false}))}});
accounts.forEach(account => parents[account.ParentId].items.push(parents[account.Id]));
component.set("v.data", parents[undefined].items);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment