This post explains how to display reference object fields data in the lightning data table in lightning web components(lwc)
HTML code
Javascript Controller
Apex Class
Result
HTML code
<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'
}, {
label: 'Opportunity Owner',
fieldName: 'OpportunityOwner',
type: 'text'
}, {
label: 'CreatedDate',
fieldName: 'CreatedDate',
type: 'date'
}
];
export default class ReferenceDataInLwcDatatable extends LightningElement {
@track data = [];
@track columns = columns;
@wire(getOppdata)
opp({error, data}) {
if(data) {
let currentData = [];
data.forEach((row) => {
/*
* Creating the an empty object
* To reslove "TypeError: 'set' on proxy: trap returned falsish for property"
*/
let rowData = {};
rowData.Name = row.Name;
rowData.CreatedDate = row.CreatedDate;
// Account related data
if (row.Account) {
rowData.AccountName = row.Account.Name;
rowData.AccountOwner = row.Account.Owner.Name;
}
// Owner releated data
if (row.Owner) {
rowData.OpportunityOwner = row.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, Owner.Name, CreatedDate FROM Opportunity LIMIT 10];
}
}
Result
this apex class is not correct according to js code . make it correct
ReplyDeleteIf the field is empty, eventhough field should display empty field. Please let me know.
ReplyDeleteIf field is empty even though the field should display empty value. It should not effect other fields on displaying in table. Provide provide code with if else condition
ReplyDeletewhat if we want to get data from child record?
ReplyDelete