How to show Parent Record Details in custom data table with iterator in Salesforce LWC?

How to show Parent Record Details in custom data table with iterator in Salesforce LWC?

Sample Code:

HTML:

<template>
    <div class="slds-box slds-theme--default">
        <table class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_striped">
            <thead>
                <tr class="slds-line-height_reset">
                    <th class="" scope="col">
                        Account Name
                    </th>
                    <th class="" scope="col">
                        Account Number
                    </th>
                    <th class="" scope="col">
                        Owner
                    </th>
                </tr>
            </thead>
            <tbody>
                <template iterator:it={records}>
                    <tr class="slds-hint-parent" key = {it.value.Id}>
                        <td data-label="Account Name">
                            <div class="slds-cell-wrap">{it.value.Name}</div>
                        </td>
                        <td data-label="Account Number">
                            <div class="slds-cell-wrap">{it.value.AccountNumber}</div>
                        </td>
                        <td data-label="Owner">
                            <div class="slds-cell-wrap">{it.value.OwnerName}</div>
                        </td>
                    </tr>
                </template>
            </tbody>
        </table>
    </div>
</template>

JavaScript:

import { LightningElement, wire } from 'lwc';
import fetchAccounts from '@salesforce/apex/AccountController.fetchAccounts';

export default class Sample extends LightningElement {

    records;
    error;

    @wire( fetchAccounts )  
    wiredAccount( { error, data } ) {
        if ( data ) {

            let rows = JSON.parse( JSON.stringify( data ) );
                
            for ( let i = 0; i < rows.length; i++ ) {  

                let dataParse = rows[ i ];

                if ( dataParse.hasOwnProperty( "Owner" ) ) {

                    if ( dataParse.Owner.hasOwnProperty( "Name" ) )
                        dataParse.OwnerName = dataParse.Owner.Name;

                }
                
            }
                
            this.records = rows;
            this.error = undefined;

        } else if ( error ) {

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

        }
    }  

}

Apex Class:

public with sharing class AccountController {
 
    @AuraEnabled( cacheable = true )
    public static List< Account > fetchAccounts() {
     
        return [ SELECT Id, Name, Industry, Rating, Type, AccountNumber, Phone, Owner.Name FROM Account LIMIT 10 ];
         
    }
     
}

Output:

Leave a Reply