How to Hyperlink parent column in lightning-datatable in Salesforce Lightning Web Component(LWC)?

How to Hyperlink parent column in lightning-datatable in Salesforce Lightning Web Component(LWC)?

Sample Code:

Apex Class:

public with sharing class ContactController {   
     
    @AuraEnabled( cacheable=true )
    public static List < Contact > fetchContacts() {

        return [
            SELECT Id, FirstName, LastName, Phone, AccountId, Account.Name
            FROM Contact LIMIT 10
        ];
        
    }

}

Lightning Web Component:

HTML:

<template>      
    <lightning-card title="Contacts" icon-name="custom:custom63">  
        <div class="slds-m-around_medium">  
            <template if:true={availableContacts}>      
                <lightning-datatable
                    key-field="Id"
                    data={availableContacts}
                    columns={columns}
                    hide-checkbox-column="true"
                    show-row-number-column="true">
                </lightning-datatable>  
            </template>      
            <template if:true={error}>  
                {error}>                  
            </template>  
        </div>  
    </lightning-card>
</template>

JavaScript:

import { LightningElement, wire } from 'lwc';
import fetchContacts from '@salesforce/apex/ContactController.fetchContacts';
 
const columns = [   
    { label: 'Account Name', fieldName: 'AccountURL', type: 'url',
    typeAttributes: { label: { fieldName: 'AccountName' }, target: '_blank'} },
    { label: 'FirstName', fieldName: 'FirstName' },
    { label: 'LastName', fieldName: 'LastName' },
    { label: 'Phone', fieldName: 'Phone' }
];

export default class ContactDataTable extends LightningElement {
     
    availableContacts;
    error;
    columns = columns;

    @wire( fetchContacts )  
    wiredAccount( { error, data } ) {

        if ( data ) {

            let tempRecs = [];
            console.log( 'Fetched Data - ' + JSON.stringify( data ) );
            data.forEach( ( record ) => {
                let tempRec = Object.assign( {}, record );  

                if ( tempRec.AccountId ) {

                    tempRec.AccountName = tempRec.Account.Name;
                    tempRec.AccountURL = '/' + tempRec.AccountId;

                }
                
                tempRecs.push( tempRec );
                
            });
            this.availableContacts = tempRecs;
            this.error = undefined;

        } else if ( error ) {

            this.error = error;
            this.availableContacts = 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