function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Paridhi Bindal 9Paridhi Bindal 9 

Display Account Name instead of ID in LWC Datatable

Hello, I am displaying custom object records in Datatable via @wire, Since account is a lookup, it displays account id instead of account name. How can I display the name of the account in the colum. 

I have tried the following but it doesn't work. Please suggest.
 {
        label: 'My Accounts',
        fieldName:'My_Account__r.Name
        type: 'text',
        sortable: true
  }
 
Best Answer chosen by Paridhi Bindal 9
Maharajan CMaharajan C
Hi Paridhi,

You can't traverse the parent details directly in datatable using dot operator. As an alternate we can use the below way:

Change the wire a property in wire a function for fetching the data to datatable. Then overide the data using JS.

Solution 1:
 
@track data;
@wire(getRecords)
wireddata({ error, data }){
   if (data) 
   {
	  this.data =  data.map(
	  record => Object.assign(
		{ "My_Account__r.Name": record.My_Account__r.Name},
		record
	    )
		);
	 
	}
else if (error) {
		this.error = error;
		this.data = undefined;
	}
}
https://www.srinivas4sfdc.com/2019/11/how-to-access-parent-object-or.html

Solutions 2:
{
	label: 'My Accounts',
	fieldName:'AccountName',
	type: 'text',
	sortable: true
}

@track data

@wire(getRecords)
 wireddata(result) {
     if (result.data) {
         this.data = result.data.map(row=>{
             return{...row, AccountName: row.My_Account__r.Name}
         })
         this.error = undefined;

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

}
https://salesforce.stackexchange.com/questions/293088/lwc-salesforce-get-parent-in-datatable-column
https://salesforce.stackexchange.com/questions/287262/flatten-data-to-display-it-using-lightning-datatable-in-lwc
https://salesforce.stackexchange.com/questions/290393/lwc-relationship-fields-in-data-table-flattening-in-wire


Thanks,
Maharajan.C

All Answers

Maharajan CMaharajan C
Hi Paridhi,

You can't traverse the parent details directly in datatable using dot operator. As an alternate we can use the below way:

Change the wire a property in wire a function for fetching the data to datatable. Then overide the data using JS.

Solution 1:
 
@track data;
@wire(getRecords)
wireddata({ error, data }){
   if (data) 
   {
	  this.data =  data.map(
	  record => Object.assign(
		{ "My_Account__r.Name": record.My_Account__r.Name},
		record
	    )
		);
	 
	}
else if (error) {
		this.error = error;
		this.data = undefined;
	}
}
https://www.srinivas4sfdc.com/2019/11/how-to-access-parent-object-or.html

Solutions 2:
{
	label: 'My Accounts',
	fieldName:'AccountName',
	type: 'text',
	sortable: true
}

@track data

@wire(getRecords)
 wireddata(result) {
     if (result.data) {
         this.data = result.data.map(row=>{
             return{...row, AccountName: row.My_Account__r.Name}
         })
         this.error = undefined;

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

}
https://salesforce.stackexchange.com/questions/293088/lwc-salesforce-get-parent-in-datatable-column
https://salesforce.stackexchange.com/questions/287262/flatten-data-to-display-it-using-lightning-datatable-in-lwc
https://salesforce.stackexchange.com/questions/290393/lwc-relationship-fields-in-data-table-flattening-in-wire


Thanks,
Maharajan.C
This was selected as the best answer
ravi soniravi soni
hi Paridhi,
get reference following dummy lwc.
/*JS*/
import { api, LightningElement, track, wire } from 'lwc';
import  fetchvechile from '@salesforce/apex/viewapex.fetchvechile';
const columns =  [{ label: 'Name', fieldName: 'Name' }, 
{ label: 'Account Name', fieldName: 'AccounttName' },
];

export default class DataTableExapmle extends LightningElement {
    recData;
    columns;
    @wire(fetchvechile)
    wiredAccounts({ error, data }) {
        if (data) {
        let sData = JSON.parse(JSON.stringify(data));
        console.log('sData : ' + JSON.stringify(sData));
        sData.forEach(function(item){
            console.log('item : ' + JSON.stringify(item));
                item.AccounttName = item.Account!=undefined ? item.Account.Name : '';
            });
            this.recData =sData; 
           this.columns = columns;
            this.error = undefined;
          } 
          else if (error) {
            this.error = error;
            this.data = undefined;
        }
    }
 
<!--HTML-->
 <lightning-datatable key-field="Id" 
                                 data={recData} 
                                 columns={columns} >
            </lightning-datatable>
 
//apex
public with sharing class viewapex {
    @AuraEnabled(cacheable=true)
   
    public static list<Contact> fetchvechile(){
        return [SELECT Id,Name,AccountId,Account.Name From Contact Limit 10];
    }
}

we are expacting that account is like a parent.
Let me know if it helps you and marking it as best.
Thank You
Suraj Tripathi 47Suraj Tripathi 47
Hi Paridhi Bindal,
you can take look for the below link example for your solution
HTML:
<template>
    <lightning-card title="Showing Reference Fields Data in Lightning Datatable">
        <lightning-datatable columns={columns} 
                            data={data} 
                            key-field="id"
                            hide-checkbox-column="true"
                            show-row-number-column="true"></lightning-datatable>
    </lightning-card>
</template>



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

// importing Apex Class
import getOppdata from '@salesforce/apex/LWCExampleController.retriveOpportunities';

// Datatable Columns
const columns = [
    {
        label: 'Opportunity Name',
        fieldName: 'Name',
        type: 'text',
    }, {
        label: 'Account Name',
        fieldName: 'AccountName',
        type: 'text'
    }, {
        label: 'Account Owner',
        fieldName: 'AccountOwner',
        type: 'text'
   
];
export default class ReferenceDataInLwcDatatable extends LightningElement {
    @track data = [];
    @track columns = columns;

    @wire(getOppdata)
    opp({error, data}) {
        if(data) {

            let currentData = [];

            data.forEach((row) => {

                let rowData = {};

                rowData.Name = row.Name;
                
                // Account related data
                if (row.Account) {
                    rowData.AccountName = row.Account.Name;
                    rowData.AccountOwner = row.Account.Owner.Name;
                }
                currentData.push(rowData);
            });

            this.data = currentData;
        }
        else if(error) {
            window.console.log(error);
        }
    }
}


Apex class:
public inherited sharing class LWCExampleController {    
    @AuraEnabled(cacheable=true)
    public static list<Opportunity> retriveOpportunities() {
        return [SELECT Id, Name, Account.Name, Account.owner.name FROM Opportunity LIMIT 10];
    }
}
For Refrence :
https://www.salesforcecodecrack.com/2019/10/display-reference-data-in-lwc.html


If you find your solution than please mark as best answer
Thanks and Regards,
Suraj Tripathi
Pavushetti Abhilash 3Pavushetti Abhilash 3
Hi Maharajan C. Your solution1 was working fine. But I got a small issue that when I dont give the account name my entire component is getting error. Saying that Name undefined. When I gave the account name its displaying, when i left empty in account field entire comp getting error. Atleast the table should display with empty field. Can you provide the code that field should display when user give input otherwise the field should be empty when user not selected account. Can you get rid of this with if-else condition.User-added image
Maharajan CMaharajan C
Hi Abhilash,

To avoid that exception please follow the below steps:

1.  In SOQL query add that lookup field api name to check the lookup has value or not from JS : (for exam: my Lookup field API Name is :  My_Account__c )
 
[Select Id, Name, My_Account__c, My_Account__r.Name,Records__c from BatchLeadConvertErrors__c limit 5];

2. Update the JS like below.
 
import { LightningElement, api, track, wire } from 'lwc';
import getRecords from "@salesforce/apex/dataTableController.getActivity";
const columns = [
    { label: 'Id', fieldName: 'Id' },
    { label: 'Name', fieldName: 'Name' },
    { label: 'Account Name', fieldName: 'My_Account__r.Name' },
    { label: 'Account Name', fieldName: 'My_Account__c' },
    { label: 'Status', fieldName: 'Records__c' }
];

export default class DatatablewithCOR extends LightningElement {
    @track data;
    @track columns = columns;
    @wire(getRecords)
    wireddata({ error, data }){
    if (data) 
    {    
        alert(' *** ' + JSON.stringify(data));
        this.data =  data.map(
        record => Object.assign(
            { "My_Account__r.Name": (record.My_Account__c != null && record.My_Account__c != '') ? record.My_Account__r.Name: '' },
            record
            )
            );
        
        }
    else if (error) {
            this.error = error;
            this.data = undefined;
        }
    }
}

Thanks,
Maharajan.C
Pavushetti Abhilash 3Pavushetti Abhilash 3
Thank you Maharajan. Above code has no errors but component getting error when on load. Saying that My_Account__r.Name is not defined. I have four fields. Two fields working fine. Another two fields getting error. Could you help out of this.
Thank you.
Nikitha VuppalanchiNikitha Vuppalanchi

Hi Abhilash,

Just have an if condition to check if My_Account__c is not undefined and then make the assignment 

Something like this
 

if(My_Account__c){
​​​​​    record => Object.assign(......
}
Gabriel LinusGabriel Linus
Hello Paridhi,

I assume that your issue has been resolved. Additionally, I have a suggestion for you. Make sure to check out the article at https://logcodes.com/lwc-datatable-in-salesforce/. It provides a comprehensive guide on how to use the Lightning Data Table in Salesforce. This guide covers handling row selection actions, implementing sorting, and enabling pagination functionality. It's a valuable resource to enhance your Salesforce development skills!