Add Related Fields Columns in Salesforce LWC Data Table : Bijay Kumar

Add Related Fields Columns in Salesforce LWC Data Table
by: Bijay Kumar
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary of the Content This tutorial explains how to add related field columns in a Salesforce Lightning Web Component (LWC) data table. Salesforce uses objects with related lists to display records linked through lookup or master-detail relationships. The tutorial focuses on fetching and displaying related fields, such as Account Name and Owner Name, in an LWC data table. **Key Steps:** 1. **Create a Controller Class:** This class fetches contact records and their related fields using SOQL queries. 2. **LWC Component Creation:** An HTML template is created to render the data table. 3. **Data Transformation:** JavaScript code is used to format the fetched data for display in the data table. 4. **Component Visibility:** The component is made visible on Lightning pages by configuring the `meta.xml` file. 5. **Deployment:** The LWC component is deployed to the Lightning page using the Lightning App Builder. The tutorial also includes an example of displaying related contact records on an account record page, emphasizing how to fetch contacts related to a specific account. ### Additional Context - **LWC (Lightning Web Component):** A modern framework for building user interfaces on the Salesforce platform. - **SOQL (Salesforce Object Query Language):** A query language used to retrieve data from Salesforce databases. - **@wire Decorator:** A feature in LWC that allows you to read Salesforce data reactively. ### Conclusion By following this tutorial, Salesforce developers can effectively display related fields in LWC data tables, enhancing the user experience by allowing users to view related information without navigating away from the current record. ### Relevant Hashtags for SEO #Salesforce #LWC #LightningWebComponents #DataTable #SOQL #SalesforceDevelopment #SalesforceTutorial #LightningComponents #SalesforceAdmin #WebDevelopment #CRM #CloudComputing #SalesforceTips


In Salesforce, we have objects with related lists displayed on the record page of each record. The related lists show a list of records linked to the current record through a lookup or master-detail relationship, to view related information without leaving the current record page.

When it comes to the related field column in the LWC data table, we fetch the data of the object’s related fields and display them in the object data table along with other fields.

In this Salesforce tutorial, we will learn how to add related field columns to the Salesforce LWC data table.

Add Related Fields Columns in LWC Data Table

To add related fields as a column in LWC data table, we need the fields from a parent or lookup object. For example, displaying the accounts related to contact records on the data table.

To fetch the Account name, we can refer to it in the SOQL query as Account.Name, but the LWC lightning data table does not support dot notation fields and does not render them in the data table.

To display the related list columns in LWC data table, we need to format them using the flatten transformation feature.

In the below example, we will display the contact records along with the related list columns Account name and the Owner Name.

1. First, define a controller class to fetch the contact records and the related list fields Account name and Owner name (contact owner).

public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getRelatedContacts() {
        return [SELECT Id, Name, Account.Name, Owner.Name 
        FROM Contact 
        LIMIT 10];
    }
}

2. Now, create an LWC component and enter the code below in the HTML template to render data in LWC data table.

<template>
    <lightning-card title="Contacts with related fields"></lightning-card>
    <lightning-datatable
        key-field="Id"
        data={data}
        columns={columns}
        hide-checkbox-column="true"
    ></lightning-datatable>
</template>

3. We transformed the data using the code below in the JS file to format the related lists column for display in the LWC data table.

import { LightningElement, wire } from 'lwc';
import getRecords from '@salesforce/apex/ContactController.getRelatedContacts';

export default class RelatedListDataTable extends LightningElement {
    
    columns = [
        { label: 'Record Name', fieldName: 'Name', type: 'text' },
        { label: 'Account Name', fieldName: 'AccountName', type: 'text' },
        { label: 'Owner Name', fieldName: 'OwnerName', type: 'text' }
    ];

    data = []; 
    @wire(getRecords)
    wiredRecords({ error, data }) {
        if (data) {
            this.data = data.map(record => ({
                Id: record.Id,
                Name: record.Name,
                AccountName: record.Account ? record.Account.Name : '', 
                OwnerName: record.Owner ? record.Owner.Name : ''
            }));
        } else if (error) {
            console.error('Error fetching records:', error);
        }
    }
}

In the above method, we have used the @wire decorator to link the fetched records to the wiredRecords function, which processes the data. If data is returned, it maps each record into an object with Id, Name, AccountName, and OwnerName, storing it in this.data.

For example, mapped AccountName in the table from the fetched value Account.Name using AccountName: record.Account ? record.Account.Name.

4. Make the component visible to the Lightning pages using the below code in the meta.xml file inside <LightningComponentBundle> tag

<isExposed>true</isExposed>

    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>

5. After this, deploy the LWC component to the Lightning page. To deploy the component navigate on the lightning page > settings > Edit page.

In the lightning app builder, add the component to the page region and save the changes.

Now you will see the data table with the contact record name, their related account, and related user(owner) names in the table columns.

Related Fields Columns in Salesforce LWC Data Table

This way, we can add the related fields columns to the Salesforce LWC Lightning data table by following the above steps.

Create Related Fields LWC Data Table for Record Page

To create a related fields LWC data table, let’s take an example, where we have to display related contact records on the account record page, to display those contact records in a custom LWC data table.

This LWC data table will display the contacts related to that specific account record.

1. Create a controller class to fetch the contacts related to specific account using the account id.

public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getRelatedContacts(String accountId) {
        return [SELECT Id, FirstName, LastName, Email, Phone 
                FROM Contact 
                WHERE AccountId = :accountId 
                LIMIT 10];
    }
}

2. Now, create an LWC component and enter the below code in the HTML file to render the data in LWC table.

<template>
    <lightning-card title="Related Contacts">
        <div class="slds-m-around_medium">
            <template if:true={contacts}>
                <lightning-datatable
                    key-field="Id"
                    data={contacts}
                    columns={columns}
                    hide-checkbox-column="true">
                </lightning-datatable>
            </template>
        </div>
    </lightning-card>
</template>

3. After this, enter the below code in the JS file defining the logic to map the related list field along the object field columns.

import { LightningElement, api, wire } from 'lwc';
import getRelatedContacts from '@salesforce/apex/ContactController.getRelatedContacts';

const COLUMNS = [
    { label: 'First Name', fieldName: 'FirstName', type: 'text' },
    { label: 'Last Name', fieldName: 'LastName', type: 'text' },
    { label: 'Email', fieldName: 'Email', type: 'email' },
    { label: 'Phone', fieldName: 'Phone', type: 'phone' }
];

export default class RelatedContacts extends LightningElement {
    @api recordId; 
    contacts; 
    error; 
    columns = COLUMNS; 
    @wire(getRelatedContacts, { accountId: '$recordId' })
    wiredContacts({ error, data }) {
        if (data) {
            this.contacts = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.contacts = undefined;
            console.error('Error retrieving contacts:', error);
        }
    }
}

In the above code, we have defined a columns array to display the related contacts of accounts. After this, we have used @api recordId to get the Account Id from the record page, which is then used to query related Contacts via the controller class method getRelatedContacts.

The @wire decorator ensures that getRelatedContacts method is fetchs related contacts with account recordId. Then wiredContacts function assigns the returned data in table using this.contacts or logs errors using this.error.

4. After this enter the below code in the meta.xml file inside the <LightningComponentBundle> tag to make this page available to the account record page.

<isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage">
            <objects>
                <object>Account</object>
            </objects>
        </targetConfig>
    </targetConfigs>

We have to show the contacts related to a specific account, so according to logic, the data table is specifically for the account record page.

5. Now, go to the account record page, click the settings icon, and select Edit page.

6. In the Lightning app builder, drag and drop the LWC component to the page region and save the changes.

Salesforce Lightning Data table with related records

Now, you will see the data table will show the related contact records for the current account record.

Create a LWC data table with related rcords on record page

This way, we can fetch the data of related records of any specific object and display it in the LWC lightning data table.

Conclusion

In this Salesforce tutorial, we have learned how to add related field columns in LWC data table, where we fetched the associated fields from the apex class and displayed in the data table column after formatting the related records into objects.

Along with this, we also created a LWC data table, to display the related object record fields in the data table. In this, we displayed the contacts related to the specific account record on the account record page.

You may also like to read:

The post Add Related Fields Columns in Salesforce LWC Data Table appeared first on SalesForce FAQs.


February 28, 2025 at 01:31PM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce