Lightning Web Component Tree Example

Let us discuss here how to use the Lightning Web Component Tree. A lightning-tree component displays the visualization of a structural hierarchy, such as a sitemap for a website or a role hierarchy in an organization. Items are displayed as hyperlinks and items in the hierarchy can be nested. Items with nested items are also known as branches.

please refer this link to Lightning web component environment setup.

1.Create Apex Class 

Use the following SFDX command to create apex class

sfdx force:apex:class:create -n TreeEx3   -d force-app/main/default/apex

Here is the apex code

public with sharing class TreeEx3 {
   @AuraEnabled(cacheable=true)
    public static List<AccountWrapper> getTreeData(){
        List<Account> accs = [Select Id , Name,(Select Id , Name from Contacts) from Account];
        List<AccountWrapper> aooo = new List<AccountWrapper>();
        for(Account a : accs){
            AccountWrapper aWraper = new AccountWrapper() ; 
            aWraper.name =a.Name ;
            aWraper.label =a.Name ;
            aWraper.expanded =true ;
            List<Items> co = new List<Items>();
            for(Contact c : a.Contacts){
                Items conWrapp = new Items();
                conWrapp.name =c.Name ;
                conWrapp.label =c.Name ;
                conWrapp.expanded =true ;
                co.add(conWrapp);
            }
            aWraper.items = co;
            aooo.add(aWraper);
            
        }
       return aooo;
    } 
    public Class AccountWrapper{
        @AuraEnabled
        public String name{get;set;}
        @AuraEnabled
        public String label{get;set;}
        @AuraEnabled
        public Boolean expanded{get;set;}
        @AuraEnabled
        public List<Items> items{get;set;}
        
    }
    public Class Items{
        @AuraEnabled
        public String name{get;set;}
        @AuraEnabled
        public String label{get;set;}
        @AuraEnabled
        public Boolean expanded{get;set;}
    }
    
}

2.Create a Lightning Web Component 

Create a Lightning web component using the following SFDX command.

sfdx force:lightning:component:create --type lwc -n TreeEx3 -d force-app/main/default/lwc

Here is the TreeEx3.html code

<template>
<h3> Tree web component Example </h3>
    <lightning-tree items={treeItems}>
    </lightning-tree>

</template>

Here is the TreeEx3.js JavaScript controller code

import {
    LightningElement,
    track,
    api,
    wire
} from 'lwc';
import getTreeData from '@salesforce/apex/TreeEx3.getTreeData';
export default class TreeEx3 extends LightningElement {
     @track treeItems;
     @track error;
     @wire(getTreeData)
     wireTreeData({
         error,
         data
     }) {
         if (data) {
             this.treeItems = data;
             console.log(JSON.stringify(data, null, '\t'));
         } else {
             this.error = error;
         }
     }
}

Here are the TreeEx3.js-meta.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

3. Push changes to scratch org. 

Push changes to scratch using this command and add this component to record page using lighting app builder.

sfdx force:source:push

After adding the lightning web component to record page using the app builder. you can able to see the tree as shown below

 

 

 

Lightning Web Component Tree Grid

Let us discuss here how to use  Lightning Web Component Tree Grid.A lightning-tree-grid component displays hierarchical data in a table. Its appearance resembles lightning-datatable, with the exception that each row can be expanded to reveal a nested group of items. Rows that contain nested data display a chevron icon to denote that they can be expanded or collapsed. This visual representation is useful for displaying structured data such as account hierarchy or forecasting data. Each column’s formatting is determined by its data type. For example, a phone number is displayed as a hyperlink with the tel: URL scheme by specifying the phone type. The default type is text .

Please refer to this link for Lightning web component environment setup 

 

1.Apex Class 

Create an apex class using the below SFDX command

sfdx force:apex:class:create -n TreeGrid   -d force-app/main/default/apex

Use this apex code in the TreeGrid Class

public with sharing class TreeGrid {
   @AuraEnabled(cacheable=true)
    public static List<AccountWrapper> getTreeGridData(){
        List<Account> accs = [Select Id , Name,(Select Id , Name from Contacts) from Account];
        List<AccountWrapper> aooo = new List<AccountWrapper>();
        for(Account a : accs){
            AccountWrapper aWraper = new AccountWrapper() ; 
            aWraper.name =a.Name ;
            aWraper.label =a.Name ;
            List<Items> co = new List<Items>();
            for(Contact c : a.Contacts){
                Items conWrapp = new Items();
                conWrapp.name =c.Name ;
                conWrapp.label =c.Name ;
                co.add(conWrapp);
            }
            aWraper.items = co;
            aooo.add(aWraper);
            
        }
        return aooo ;
    } 
    public Class AccountWrapper{
        @AuraEnabled
        public String name {get;set;}
        @AuraEnabled
        public String label {get;set;}
        @AuraEnabled
        public List<Items> items {get;set;}
    }
    public Class Items{
        @AuraEnabled
        public String name {get;set;}
        @AuraEnabled
        public String label {get;set;}
        @AuraEnabled
        public List<Items> items {get;set;}
    }
}

 

2. Create a Lightning web component 

Create a lightning web component using this below SFDX Command

sfdx force:lightning:component:create --type lwc -n TreeGrid -d force-app/main/default/lwc

Here is the code for TreeGrid.html

<template>
    <h4> Tree Grid Example</h4>
    <lightning-tree-grid data={treeItems} columns={columns} key-field="name">
    </lightning-tree-grid>
</template>

Here is the TreeGrid.js JavaScript controller

import {
    LightningElement,
    track,
    api,
    wire
} from 'lwc';
import getTreeGridData from '@salesforce/apex/TreeGrid.getTreeGridData';

export default class TreeGrid extends LightningElement {
    @track columns = [{
            type: 'text',
            fieldName: 'name',
            label: 'name'
        },
        {
            type: 'text',
            fieldName: 'label',
            label: 'label'
        }
    ];
     @track treeItems;
     @track error;
     @wire(getTreeGridData)
     wireTreeData({
         error,
         data
     }) {
         if (data) {
             //  alert(data);
             var res = data;
             var tempjson = JSON.parse(JSON.stringify(data).split('items').join('_children'));
             console.log(tempjson);
             this.treeItems = tempjson;
             console.log(JSON.stringify(tempjson, null, '\t'));
         } else {
             this.error = error;
             //  alert('error' + error);
         }
     }
}

Here are the TreeGrid.js-meta.xml configuration files

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

3.Push Changes to scratch org 

Now push the changes to scratch org using this SFDX command

sfdx force:source:push

Add this component to the record page using the lightning app builder. After adding to the record page you can able to the Tree grid as shown below

 

 

 

Lightning Web Component Google Maps

Let us discuss here how to use the Google maps with Lightning Web Component Map. A lightning-map component displays a map of one or more locations. To display maps Pass the location to be displayed via the component’s map-markers property. map-markers is an array of markers that indicate location. A marker contains

  • Location Information: This can be a coordinate pair of latitude and longitude or an address composed of address elements.
  • Descriptive Information: This is information like title, description and an icon which is information relevant to the marker but not specifically related to location.

The location information supports the following address elements: City, Country, PostalCode, State, and Street. Note that to support reliable geocoding of addresses, if Street is specified then at least one of City, Country, PostalCode or State must be specified. Here’s an example of a marker that uses address elements.

 

[{
    location: {
        'City': 'San Francisco',
        'Country': 'USA',
        'PostalCode': '94105',
        'State': 'CA',
        'Street': 'The Landmark @ One Market, Suite 300'
    },
    title: 'The Landmark Building',
    description: 'The Landmark is considered to be one of the city's most architecturally distinct and historic properties',
    icon: 'standard:account'
}]

Here’s an example of a marker that uses coordinates for latitude and longitude.

{
    location: {
        'Latitude': '37.790197',
        'Longitude': '-122.396879'
    }
}

 

For each map marker in the array of map markers, provide either latitude and longitude coordinates or address elements. If you specify both in a single marker, latitude and longitude get precedence.

When displaying a list of addresses, you must also pass the markers-title property, which displays a heading for your locations.

1.Create an Apex Class

The following apex class will get the account location information and pass it to the web components. Use the following SFDX command.

sfdx force:apex:class:create -n AccountLocation  -d force-app/main/default/apex

Here is the code

public class AccountLocation {
    @AuraEnabled(cacheable=true)
    public static List<Location> getAccount() {
        List< Account> accs =  [Select Id, Name,Type, Industry, BillingAddress,BillingStreet,
                                BillingCity, BillingCountry, BillingPostalCode,
                                BillingState,Phone from Account where BillingStreet!=NULL AND
                                BillingCity!=NULL AND BillingCountry!=NULL AND  BillingPostalCode!=NULL AND
                                BillingState!=NULL] ;
        
        List<Location> loc = new List<Location>();
        for(Account acc :accs){
            System.debug(acc);
            GeoLocation geoInfo = new GeoLocation();
            geoInfo.Street = acc.BillingStreet;
            geoInfo.PostalCode = acc.BillingPostalCode;
            geoInfo.City = acc.BillingCity;
            geoInfo.State = acc.BillingState;
            geoInfo.Country = acc.BillingCountry;
            Location locDetail = new Location();
            locDetail.icon = 'action:map'; 
            locDetail.title = acc.Name;
            locDetail.description = acc.Name;
            locDetail.location = geoInfo;
            
            loc.add(locDetail);
        }
        return loc ;
    }
    public class Location{
        @AuraEnabled 
        public String icon{get;set;} 
        @AuraEnabled 
        public String title{get;set;} 
        @AuraEnabled
        public String description{get;set;} 
        @AuraEnabled 
        public GeoLocation location{get;set;} 
    }
    public class GeoLocation{
        @AuraEnabled 
        public String Street{get;set;}
        @AuraEnabled 
        public String PostalCode{get;set;}
        @AuraEnabled 
        public String City{get;set;}
        @AuraEnabled 
        public String State{get;set;}
        @AuraEnabled 
        public String Country{get;set;}
    }
}

2. Create a Lightning Web component 

Create a lightning web component to display the map. use this SFDX command to create a web component.

sfdx force:lightning:component:create --type lwc -n MapEx -d force-app/main/default/lwc

Here is the MapEx.html code

<template>
    <h6> Google Maps Example </h6>
    <template if:true={accounts}>
        <lightning-map map-markers={accounts}  markers-title={accounts}>
        </lightning-map>
    </template>
</template>

Here is the MapEx.js JavaScript controller code

import { LightningElement ,api,wire,track} from 'lwc';
import getAccount from '@salesforce/apex/AccountLocation.getAccount';

export default class MapEx extends LightningElement {
     @track accounts;
     @track error;
     @track showFooter = true ;
     @wire(getAccount)
     wiredAccountss({error,data}) {
         if (data) {
             this.accounts = data;
             console.log(data);
             console.log(JSON.stringify(data, null, '\t'));
         } else if (error) {
             console.log(error);
             this.error = error;
         }
     }
}

Here is the MapEx.js-meta.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

3.Push Changes to scratch org 

Now push the changes to scratch org using this below command.

sfdx force:source:push

Add this web component to the record page and you can able to see the map as shown below.

 

Lightning Web Component Datatable

Let us discuss here a simple example of Lightning Web Component Data table.A lightning-datatable component displays tabular data where each column can be displayed based on the data type. For example, an email address is displayed as a hyperlink with the mailto: URL scheme by specifying the email type. The default type is text.

1. Create an apex class 

Create an Apex class that will get all opportunities. Use the below SFDX Command

sfdx force:apex:class:create -n GetAllOpportunities -d force-app/main/default/apex

Here is the code

public with sharing class GetAllOpportunities {
   @AuraEnabled(cacheable=true)
    public static List<Opportunity> getAllOpps() {
        return [SELECT Id, Name ,StageName, CloseDate ,Type ,Probability,Account.Name from Opportunity];
    }
}

2. Create a Lightning Web Component 

Create a Lightning web component using this SFDX command. this web component will display the opportunities in the table.

sfdx force:lightning:component:create --type lwc -n DatatableEx -d force-app/main/default/lwc

Here is the DatatableEx.html code

<template>
    <h2> Data table Example -1</h2>
    <lightning-datatable data={data} columns={columns} key-field="Id">
    </lightning-datatable>
</template>

Here is the DatatableEx.js JavaScript controller code.

import { LightningElement ,api,wire,track} from 'lwc';
import getAllOpps from '@salesforce/apex/GetAllOpportunities.getAllOpps';

export default class DatatableEx12 extends LightningElement {
    @track columns = [{
            label: 'Opportunity name',
            fieldName: 'Name',
            type: 'text',
            sortable: true
        },
        {
            label: 'Stage Name',
            fieldName: 'StageName',
            type: 'text',
            sortable: true
        },
        {
            label: 'Close date',
            fieldName: 'CloseDate',
            type: 'date',
            sortable: true
        }

    ];
    @track error;
    @track data ;
    @wire(getAllOpps)
    wiredOpps({
        error,
        data
    }) {
        if (data) {
            this.data = data;
            console.log(data);
            console.log(JSON.stringify(data, null, '\t'));
        } else if (error) {
            this.error = error;
        }
    }
}

Use this DatatableEx.js-meta.xml configuration file

 

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

3. Push Changes to scratch org

Use the below SFDX command to push the changes to scratch org

sfdx force:source:push

 

Now add this component to record page using lightning app builder and save it. you can able to see the below data table with the list of opportunities.