Salesforce Lightning (LWC) Tree Grid: A Comprehensive Guide
Hierarchical data structures are integral to many Salesforce applications, often representing complex relationships between records. Salesforce Lightning Web Components (LWC) offer powerful tools to visualize such data structures efficiently. In this blog post, we'll explore how the Lightning Tree Grid component can enhance user experience by providing a clear and intuitive view of hierarchical data in Salesforce.
Implementing the Lightning Tree Grid
Data Retrieval: Use Apex methods to fetch hierarchical data from Salesforce, ensuring to include related records as needed.
public class getAccountAndContact { @AuraEnabled(cacheable=true) public static List<Account> getAllAccountsWithContacts(){ return [Select Id,name,phone,website, (Select id,Name,Phone,Email from Contacts) from Account Limit 5 ]; } }
Data Formatting: Format the retrieved data into a structure compatible with the Lightning Tree Grid component, including parent-child relationships and additional properties.
formatGridData(result){ return result.map(item => { const { Contacts, ...account } = item; return { ...account, "_children": Contacts }; } )}
Component Integration: Integrate the Lightning Tree Grid component into your Lightning Web Component (LWC) markup, specifying columns, data, and any additional configurations.
<template> <lightning-card variant="Narrow" title="Lightning Tree Grid" icon-name="standard:account"> <div class="slds-p-around_medium"> <lightning-tree-grid columns={columns} data={gridData} key-field="Name" hide-checkbox-column > </lightning-tree-grid> </div> </lightning-card> </template>
Example
In this example, we demonstrate how to use the Lightning Tree Grid component to display hierarchical data in a Salesforce Lightning Web Component (LWC). The TreeGridLwc
component fetches account records along with their associated contacts using the getAccounts
Apex method, as shown in the above code snippet. The retrieved data is then formatted for the Lightning Tree Grid. The formatGridData
method processes each account record by extracting its contacts and adding them as children using the _children
property, ensuring proper hierarchical representation. Additionally, custom properties such as Url
are added to both accounts and contacts to enable navigation to their respective detail pages. We also introduce a third level of nested data with sample records to showcase the component's capability to handle deep hierarchies. The columns
property defines the columns displayed in the grid, including fields for the account name (with a clickable URL), phone number, and website. This structured approach enables the efficient and visually appealing display of complex data relationships within Salesforce applications.
import { LightningElement, wire, track } from 'lwc';
import getAccounts from '@salesforce/apex/getAccountAndContact.getAllAccountsWithContacts';
export default class TreeGridLwc extends LightningElement {
@track gridData;
@wire(getAccounts)
accountsWithContact({ data, error }) {
if (data) {
this.gridData = this.formatGridData(data);
console.log(JSON.stringify(this.gridData));
} else if (error) {
console.log("Error:", JSON.stringify(error));
}
}
@track columns = [
{
label: "Name",
fieldName: "Url",
type: "url",
typeAttributes:{label:{fieldName:"Name"},target: "_blank"}
},
{ label: 'Phone', fieldName: 'Phone', type: 'text' },
{ label: 'Website', fieldName: 'Website', type: 'url', typeAttributes: { target: '_blank' } },
];
@track thirdLevelData =[
{
Name : "Harsh Verma",
Website: "https://forcedev.hashnode.dev/",
Url:"https://forcedev.hashnode.dev"
}
];
formatGridData(result) {
return result.map(item => {
const { Contacts, ...account } = item;
// Adding a new custom property to each account
const formattedAccount = {
...account,
Url: `/${account.Id}` // Custom property for account
};
// Ensure Contacts is an array before mapping over it
const formattedContacts = (Contacts || []).map(contact => ({
...contact,
Url: `/${contact.Id}`, // Custom property for contact
// Adding third level data to each contact
// This line maps over the thirdLevelData array and adds each item as a child of the contact
_children: this.thirdLevelData.map(data => ({
...data // Copy all properties from each object in thirdLevelData
}))
}));
return { ...formattedAccount, "_children": formattedContacts };
});
}
}
Output
Conclusion
The Lightning Tree Grid component empowers Salesforce developers to create rich and interactive user interfaces for visualizing hierarchical data. By leveraging its features and customization options, organizations can build powerful applications that streamline data analysis, enhance productivity, and drive informed decision-making.
Subscribe to my newsletter
Read articles from Harsh Verma directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by