Saturday, August 6, 2022

How to display lookup field in lightning data table in LWC?

In last blog post we see how to display values in data table in LWC. In this blog post we will see how to display lookup field in data table in LWC.

Now, let us understand the real time use of data table with an example below where we will display account records and additionally we will display the Parent Account Name as shown below.



How to display lookup field in lightning data table in LWC?



testLWCTableExample.html

<template>

    <h1>Account Data Table</h1>

<template if:true={accList}>

    <lightning-datatable

        key-field="id"

        data={accList}

        columns={columns} >

        </lightning-datatable>

</template>

<template if:true={error}>

 Some error occured.

</template>

 </template>



Note:

The data which we received from wire method is read only data and hence to display lookup values
we need to parsed data. We can use JSON.stringify to remove the reference as shown below. Once we remove the reference the data will not be read only and a new variable can now be add to the result to hold lookup values.

testLWCTableExample.js

import { LightningElement, track, wire } from 'lwc';

import getAccountList from '@salesforce/apex/AccountDataController.getAccountList';

const columns=[

{label: 'Account Name', fieldName: 'Name'},

{label: 'Account Industry', fieldName: 'Industry'},

{label: 'Account Description', fieldName: 'Description'},

{label: 'Parent Account Name', fieldName: 'Parent_Account_Name'},

];

 

export default class TestLWCTableExample extends LightningElement {

    @track error;

    @track columns = columns;

    @track accList;

    @wire (getAccountList) accList({error, data})

    {

        if(data)

        {

            let accParsedData=JSON.parse(JSON.stringify(data));

            accParsedData.forEach(acc => {

                if(acc.ParentId){

                acc.Parent_Account_Name=acc.Parent.Name;

                }

            });

            this.accList = accParsedData;

        }

        else if(error)

        {

            this.error = error;

        }

    }

   

}


testLWCTableExample.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>55.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__AppPage</target>

        <target>lightning__RecordPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>


No comments:

Post a Comment