Display Records in UI Using Lightning Tree Grid

In Salesforce, when we need to fetch a parent record (like Account) along with its related child records (such as Contacts), and display this structured data in an expandable format, we can use the lightning-tree-grid component. This component allows us to display hierarchical data in a grid format with expandable rows. It supports up to 20 nested levels of data. If more levels are required, a custom component must be created.

This blog will walk through how to fetch Accounts and their related Contacts, and display them in a Tree Grid format using lightning-tree-grid.

Key Features of lightning-tree-grid:

  • Displays hierarchical data with nested levels.

  • Supports expandable rows.

  • Automatically adds checkboxes in the first column (which can be hidden).

Component Code:

Below is the code for an LWC component that fetches Accounts with related Contacts and displays them using the lightning-tree-grid.

<template>
    <lightning-card title="Top Accounts with Contacts" icon-name="standard:account">
        <div class="slds-p-around_medium">
            <h2 class="slds-text-heading_medium slds-m-bottom_medium slds-text-color_success">
                Explore Top Accounts and their related Contacts in a structured Tree Grid format.
            </h2>
            <lightning-spinner if:true={isLoading} alternative-text="Loading data..."></lightning-spinner>

            <!-- Tree Grid -->
            <template if:true={gridData.length}>
                <div class="slds-scrollable_y slds-border_top slds-border_bottom">
                    <lightning-tree-grid 
                        hide-checkbox-column 
                        columns={gridColumns} 
                        data={gridData} 
                        key-field="Name" 
                        class="slds-table_bordered">
                    </lightning-tree-grid>
                </div>
            </template>
            <template if:false={gridData.length}>
                <p class="slds-text-align_center slds-text-color_error">No data available to display.</p>
            </template>
        </div>
    </lightning-card>
</template>

Explanation:

  • lightning-card: Creates a card with the title "Top Accounts with Contacts" and an icon (standard: account).

  • lightning-spinner: A loading spinner shown when data is being fetched.

  • lightning-tree-grid: The tree grid component to display data, with the columns and data passed as properties.

  • Conditionals (if:true, if:false): Used to show data or a "No data available" message based on whether gridData is populated.

JavaScript Controller

import { LightningElement, wire, track } from 'lwc';
import getTopAccountsWithContacts from '@salesforce/apex/TopAccountsWithContacts.getTopAccountsWithContacts';

export default class LightningTreeGridDemo extends LightningElement {
    @track gridData = [];
    @track isLoading = true;

    // Columns for the Tree Grid
    gridColumns = [
        {
            type: 'text',
            fieldName: 'Name',
            label: 'Account Name',
            initialWidth: 300,
        },
        {
            type: 'text',
            fieldName: 'Phone',
            label: 'Phone',
        },
        {
            type: 'url',
            fieldName: 'Website',
            label: 'Account Website',
            typeAttributes: { target: '_blank' },
        },
    ];

    // Dummy Contact Data
    dummyContactData = [
        {
            Name: 'John Doe',
            Email: 'john.doe@example.com',
            Website: 'https://www.example.com',
        },
    ];

    // Fetch Accounts with Contacts
    @wire(getTopAccountsWithContacts)
    accountsWithContactsResult({ data, error }) {
        if (data) {
            this.gridData = this.formatGridData(data);
            this.isLoading = false;
        } else if (error) {
            console.error('Error fetching data:', error);
            this.isLoading = false;
        }
    }

    // Format Data for Tree Grid
    formatGridData(result) {
        return result.map(item => {
            const { Contacts, ...accountDetails } = item;
            let updatedContacts = [];
            if (Contacts && Contacts.length > 0) {
                updatedContacts = Contacts.map(contact => ({
                    ...contact,
                    "_children": this.dummyContactData,
                }));
            }
            return { ...accountDetails, "_children": updatedContacts };
        });
    }
}

Explanation:

  • @wire(getTopAccountsWithContacts): Fetches the top 5 Accounts along with their related Contacts using the Apex method getTopAccountsWithContacts.

  • gridColumns: Defines the columns for the tree grid, including fields for Account Name, Phone, and Website.

  • formatGridData: This method processes the data returned from the Apex method and prepares it for display in the tree grid.

  • Dummy Contact Data: A fake contact data is added to the contacts in order to establish an additional level of hierarchy. to confirm that the second stage of expansion is functioning.

Apex Class: Fetch Accounts and Contacts

The Apex class fetches the top 5 recently created Accounts and their related Contacts.

javaCopy code/**
* @File Name          : TopAccountsWithContacts.cls
* @Description        : Apex class to fetch the top 5 most recently created Accounts along with their related Contacts.
* @Author             : Ranjith Raja
* @Last Modified By   : Ranjith Raja
* @Last Modified On   : December 1, 2024
* @Modification Log   :
* ============================================================================
* Ver   | Date           | Author        | Modification
* ============================================================================
* 1.0   | December 1, 2024 | Ranjith Raja | Initial Version
*/

public class TopAccountsWithContacts {
    /**
    * @Description: Fetches the top 5 most recently created Accounts along with their related Contacts.
    * @return List<Account>: List of Accounts with their related Contacts.
    */
    @AuraEnabled(cacheable=true)
    public static List<Account> getTopAccountsWithContacts() {
        return [
            SELECT Id, Name, Phone, Website, 
                   (SELECT Id, Name, Email, Phone FROM Contacts) 
            FROM Account 
            ORDER BY CreatedDate DESC 
            LIMIT 5
        ];
    }
}

Explanation:

  • getTopAccountsWithContacts: This method retrieves the top 5 most recently created Accounts and includes their related Contacts.

  • The query uses the INNER SELECT to get Contacts related to each Account.

Key Points:

  1. Tree Grid Component: A powerful component for displaying hierarchical data.

  2. Expandable Data: Child records (Contacts) are displayed under their parent Account record.

Final Screen:

Conclusion:

The lightning-tree-grid component offers a great way to display hierarchical data in a clean, structured, and expandable format. In this blog, we demonstrated how to use it to display Accounts and their related Contacts. With the power of Apex and LWC, you can easily build such components to meet your data display requirements.

By following this approach, you can leverage the lightning-tree-grid component to create beautiful, interactive UIs for displaying parent-child record relationships in Salesforce.

Thank you for reading! Feel free to reach out with any questions or feedback. Stay tuned for more Salesforce insights!

0
Subscribe to my newsletter

Read articles from Ranjith Raja Mathiyalagan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ranjith Raja Mathiyalagan
Ranjith Raja Mathiyalagan

Passionate Salesforce Developer with 6.5 years of experience in building scalable CRM solutions and delivering innovative Salesforce applications. Sharing knowledge and insights on Salesforce development, best practices, and real-world use cases. Follow for expert tips, use case documentation, and project success stories.