How to show parent records data in lighting-datatable lwc

In our previous post, we discussed how to use Lightning Datatable in LWC with Apex to show data in a tabular format. If you have followed the instructions well, it will be a piece of cake for you to use lightning-datatable in LWC. There are some complex scenarios where we may need to show related objects in the lightning-datatable. This article will guide you through the steps on How to show parent records data in lighting-datatable lwc.

Prerequisite

Scenario

For this article, we will want to show all related Contacts of an Account and its User’s record details in a lightning-datatable.

Step 1: Create an Apex Class, Query, and Return Contact records

Create an Apex class with an @AuraEnabled method that will return the List of Contact records.

The method accepts a String parameter called accountId, with this accountId we will query the contact records fields that we want to show in the lightning-datatable.

public with sharing class ContactController {
   
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContactRecords(String accountId){
        List<Contact> contactList = new List<Contact>();
        system.debug('accountId : '+accountId);
        try {

            if(accountId!=null){
                contactList = [Select id,Email,Name,Phone,Owner.Name,Owner.Username from Contact where AccountId=:accountId];
            }
            system.debug('contactList :'+contactList);
            return contactList;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

Step 2:Create LWC Component to call the apex class and show contacts and related User details in the UI

We will now create an LWC Component and call the Apex method from the javascript file.

HTML File Code

In the HTML file, we will paste the below code. Don’t worry we will explain how contactList and column values are used later in this article.

For now, we can just paste the code and understand the javascript part.

<template>
    <lightning-datatable
            key-field="id"
            data={contactList}
            columns={columns}>
    </lightning-datatable>
</template>

JS File Code

Below is the sample javascript code which makes a call to the apex class in the second line.

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

export default class RelatedAccountContacts extends LightningElement {
     columns = [
        { label: 'Email', fieldName: 'Email', type: 'email' },
        { label: 'Name', fieldName: 'Name', type: 'text' },
        { label: 'OwnerName', fieldName: 'OwnerName', type: 'text' },
        { label: 'OwnerUserName', fieldName: 'OwnerUsername', type: 'text' },
    ];
    
    @api recordId; 
    contactList;

    @wire(getContactRecords,{accountId:'$recordId'})
    contactListRec({data,error}){
        
        if(data){
            console.log('data : ',data);
            
            this.contactList = data.map(value=>{
                return{...value,OwnerName:value.Owner.Name,OwnerUsername:value.Owner.Username}
            });
        }else if(error){
            console.log('error',error);
        }
    }
}

You can find the complete explanation of this code in our previous article here. The code used here is almost identical, except for minor changes to the Columns array and the way we are handling data returned from the Apex method.

As you can see in the js code above, we are using data.map iterate over the list of records returned from Apex class and use javascript spread syntax to expand each JSON structure in one place.

Then with we create a new key OwnerName and assign it value.Owner.Name as a value similar with OwnerUsername:value.Owner.Username

This way we add new OwnerName and OwnerUsername key-value pair to the contactList.

Data Returned from ApexAfter using data.map
{
Email: “a_young@dickenson.com”,
Id: “0039000000yRHEoAAO”,
Name: “Andy Young”,
Owner: {Name: ‘Gourav Bhardwaj’, 
Username: ‘gouravbhardwaj@email.com’, 
Id: ‘12345000002jtKOAAA’},
OwnerId: “12345000002jtKOAAA”,
Phone: “(785) 241-6200”
}
Data Returned from Apex
After using data.map
{
Email: “a_young@dickenson.com”,
Id: “0039000000yRHEoAAO”,
Name: “Andy Young”,
Owner: {Name: ‘Gourav Bhardwaj’, 
Username: ‘gouravbhardwaj@email.com’, 
Id: ‘12345000002jtKOAAA’},
OwnerId: “12345000002jtKOAAA”,
Phone: “(785) 241-6200”,
OwnerName:’Gourav Bhardwaj’
OwnerUsername:’gouravbhardwaj@email.com’
}

With this new key-value pair created, it will be easier to refer to the fields in the Columns array.

Notice that in the Columns array, we are mapping the label names with the key in the JSON. This tells LWC which column name to map the values returned from Apex.

 columns = [
        { label: 'Email', fieldName: 'Email', type: 'email' },
        { label: 'Name', fieldName: 'Name', type: 'text' },
        { label: 'OwnerName', fieldName: 'OwnerName', type: 'text' },
        { label: 'OwnerUserName', fieldName: 'OwnerUsername', type: 'text' }

Time for the Final Result

You should now be able to see below table structure. You can now see how the new keys created using data.map are rendered to show data from the parent records.

How to show parent records data in lighting-datatable lwc
How to show parent records data in lighting-datatable lwc

You can read the complete documentation on lightning-datatable by Salesforce here.