How to display Account Name while displaying Contacts in Lightning Data Table in Salesforce Lightning Web Component?

How to display Account Name while displaying Contacts in Lightning Data Table in Salesforce Lightning Web Component?

Sample Code:

Apex Class:

public with sharing class ContactController {

    @AuraEnabled( cacheable=true )
    public static List < Contact > fetchContacts(){    

        return [
            SELECT Id, Name, Account.Name FROM Contact LIMIT 5
        ];

    }

}

Lightning Web Component:

HTML:

<template>
    <lightning-card>
        <lightning-datatable
                key-field="Id"
                data={records}
                columns={columns}
                hide-checkbox-column="true">
        </lightning-datatable>
    </lightning-card>
</template>

JavaScript:

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

const columns = [
    { label: 'Contact Name', fieldName: 'Name' },
    { label: 'Account Name', fieldName: 'AccName' }
];

export default class DataTable extends LightningElement {

    records;
    error;
    columns = columns;
    draftValues = [];

    @wire( fetchContacts )  
    wiredAccount( value ) {

        const { data, error } = value;

        if ( data ) {
            
            let tempRecords = JSON.parse( JSON.stringify( data ) );
            tempRecords = tempRecords.map( row => {
                return { ...row, Name: row.Name, AccName: ( row.Account ? row.Account.Name : null ) };
            })
            this.records = tempRecords;
            this.error = undefined;

        } else if ( error ) {

            this.error = error;
            this.records = undefined;

        }

    }  

}

JS-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>52.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>

Output:

Leave a Reply