Monday, December 7, 2020

Hyperlink a Record in lightning-datatable in Lightning Web Components(lwc)

 This post explains how to add the Hyperlink to name in the lightning data table using Lightning web components(lwc).

Example:

HTML Code:

<template>
    <lightning-card title="Hyperlink to The Name in Lightning Datatable"><br/>
         <div if:true={consData}>
            <lightning-datatable data={consData} 
                                 columns={columns} 
                                 key-field="Id"
                                 hide-checkbox-column="true"></lightning-datatable>
        </div>
    </lightning-card>
</template>

Javascript Code:

import { LightningElement, wire, track } from 'lwc';
import getContacts from '@salesforce/apex/LWCExampleController.getContacts';


// datatable columns
const columns = [
    {
        label: 'Name',
        fieldName: 'ConName',
        type: 'url',
        typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}
    }, {
        label: 'FirstName',
        fieldName: 'FirstName',
        type: 'text',
    }, {
        label: 'LastName',
        fieldName: 'LastName',
        type: 'text',
    }, {
        label: 'Phone',
        fieldName: 'Phone',
        type: 'phone'
    }
];

export default class HyperlinkNameInDatatable extends LightningElement {
    consData = [];
    columns = columns;

    @wire(getContacts)
    contacts({ error, data }) {

        if (data) {
            let tempConList = []; 
            
            data.forEach((record) => {
                let tempConRec = Object.assign({}, record);  
                tempConRec.ConName = '/' + tempConRec.Id;
                tempConList.push(tempConRec);
                
            });
            
            this.consData = tempConList;
            this.error = undefined;

            console.table(this.consData);

        } else if (error) {
            this.error = result.error;
        }
    }
}

Apex Code:

public inherited sharing class LWCExampleController {

    @AuraEnabled(Cacheable = true)
    public static List<Contact> getContacts() {
        return [SELECT Id, Name, FirstName, LastName, Phone, Email 
                FROM Contact 
                WHERE Email != null 
                AND Phone != null 
                ORDER BY CreatedDate DESC NULLS LAST limit 10];
    }
}

Result:



No comments:

Post a Comment