Monday 11 September 2017

Using lightning:tree to display Account Hierarchy #Salesforce Lightning Component #Winter'18

 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


Salesforce Documentation


Lightning Design System : Lightning Tree


Salesforce Release Notes Winter'18



Thanks you

30 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. When you have the
      implements="...,force:hasRecordId"
    is the
      <aura:attribute name="recordId" type="String"/>
    needed ?

    ReplyDelete
    Replies
    1. Then how you will use the recordId of Account with using recordId attribute?, I am using attribute recordId to get the account Id, if you have any other way of doing that, then you can try that one as well.

      Delete
    2. I think the aura framework does it for you. If you put the ltg component on an Account page layout then it gets the Account record id automatically because of the 'force:hasRecordId'.
      I took your example component and removed the recordId line. It works just fine without it.

      Delete
    3. Awesome, thanks for letting me know.

      Delete
  3. From Salesforce documentation:
    "If your component implements force:hasRecordId, you don’t need to add a recordId attribute to the component yourself. If you do add it, don’t change the access level or type of the attribute or the component will cause a runtime error."

    ReplyDelete
  4. Hello! Great sample. Instead of name, how do I retrieve the label? Using event.getParam('label') won't work.
    Thank ou

    ReplyDelete
  5. Hi,

    I am using the lightning:tree on a custom lightning component to show the account hierarchy. Everything is working fine except the expand/collapse icons are not visible.
    Any help would be appreciated.

    Thanks,
    RR

    ReplyDelete
    Replies
    1. Just recheck you have everything in version 41 or more.

      thanks

      Delete
  6. Hi.Thats a very helpful article.
    But Is there any way that we can add more fields on the tree along with account name.
    I would like to show more field onthe tree display instead of just name. Please guide in that regards.

    Thanks
    Swetha

    ReplyDelete
  7. Awesome post.. Good explanation. Helpful one!
    Salesforce Lightning Training

    ReplyDelete

  8. Very Impressive Salesforce Lightning tutorial. The content seems to be pretty exhaustive and excellent and will definitely help in learning Salesforce Lightning. I'm also a learner taken up Salesforce training and I think your content has cleared some concepts of mine. While browsing for Salesforce Lightning tutorials on YouTube i found this fantastic video on Salesforce Lightning. Do check it out if you are interested to know more.:-https://www.youtube.com/watch?v=SrmlBPnHqO0&t=19s

    ReplyDelete

  9. Very Impressive Salesforce Lightning tutorial. The content seems to be pretty exhaustive and excellent and will definitely help in learning Salesforce Lightning. I'm also a learner taken up Salesforce training and I think your content has cleared some concepts of mine. While browsing for Salesforce Lightning tutorials on YouTube i found this fantastic video on Salesforce.Do check it out if you are interested to know more.:-https://www.youtube.com/watch?v=MOH8Zr7hm5U

    ReplyDelete
  10. hello i have asimilar requirment but it extened to n levels a object with child and then child and son on can you help me the best design

    ReplyDelete
  11. Hi,

    Is there a way to open the link in new window or tab??

    TIA!

    ReplyDelete
  12. I would like to know more about these suggestive points. Give me little more brief and I think they can help me. Here the mentioned points are very useful and I am definitely going to adopt in my life.
    belastingconsulent amsterdam

    ReplyDelete
  13. Most of educational information over different kinds of blogs do not such supportive as supportive all the points of this blog. You need not to find any other platform to verify the data stated here.
    bioresonantie groningen

    ReplyDelete
  14. Constructor not defined: [items].(String, Boolean, List)

    error is occuring in Apex class.

    ReplyDelete
  15. codey expandable is not coming for me ,although i used the same code ...

    ReplyDelete
  16. plz reply...the codey expandable is not coming under Account Hierarchy

    ReplyDelete
  17. Get huge discount on Home and Kitchen Appliances,Split and Window Air Conditioner, Mobiles & Laptops online , Television, Speakers & more electronics at best price.
    samsung washing machine

    ReplyDelete
  18. I was eager to find this page. I needed to thank you for ones time for this especially awesome read!! I certainly truly preferred all aspects of it and I likewise have you book-set apart to look at new data in your blog.

    buy Medicare Insurance

    ReplyDelete