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

How to hyperlink 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">
                                <a href={it.value.OwnerURL}>
                                    {it.value.OwnerName}
                                </a>
                            </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 ) );
            console.log( 'Rows are ' + JSON.stringify( rows ) );
                
            for ( let i = 0; i < rows.length; i++ ) {  

                let dataParse = rows[ i ];
                dataParse.OwnerName = dataParse.Owner.Name;
                dataParse.OwnerURL = "/" + dataParse.OwnerId;
                
            }
                
            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, OwnerId FROM Account LIMIT 10 ];
         
    }
     
}

Output:

Leave a Reply