Requirement to show Account with contacts in tree like structure as below:
We can implement this above hierarchy tree like structure in lwc using <Lightning-Grid-Tree>
Lwc Code:
lwcGridTree.html
<template><lightning-button label="Collapse All" onclick={handleCollapseAll}></lightning-button><lightning-button label="Expand All" onclick={handleExpandAll}></lightning-button><lightning-tree-gridcolumns={gridColumn}data={gridData}key-field="Id"></lightning-tree-grid></template>
lwcGridTree.js
import { LightningElement,wire } from 'lwc';
import getAccountWithContact from '@salesforce/apex/SfDataController.getAccountWithAssociatedContacts';
export default class LwcGreedTree extends LightningElement {
gridData;
gridColumn = [
{
type:'text',
fieldName:'Name',
label:'Acc Name'
},
{
type:'text',
fieldName:'Id',
label:'Record Id'
},
{
type:'text',
fieldName:'FirstName',
label:'Contact FirstName'
},
{
type:'text',
fieldName:'LastName',
label:'Contact LastName'
}
]
@wire(getAccountWithContact)
accDetails({ data, error }) {
if (data) {
let accdata = JSON.parse(JSON.stringify(data));
// create grid data map
for(let i = 0; i < accdata.length;i++ ){
accdata[i]._children = accdata[i]['Contacts'];
delete accdata[i]['Contacts'];
}
this.gridData = accdata;
}
if (error){
console.log(error);
}
}
handleCollapseAll(){
const grid = this.template.querySelector('lightning-tree-grid');
grid.collapseAll();
}
handleExpandAll(){
const grid = this.template.querySelector('lightning-tree-grid');
grid.expandAll();
}
}
lwcGridTree.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>61.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
Apex Controller:
sfDataController Apex class
public without sharing class SfDataController {
@AuraEnabled (Cacheable=true)
public static List<Account> getAccountWithAssociatedContacts(){
return [SELECT id , Name,
(SELECT id , FirstName,LastName from Contacts)
From Account ];
}
}
Test Results:




No comments:
Post a Comment