Hello Guys, in this post we would learn how can we show Parent object data along with no of child in one column in Lightning data table in Lightning Web Component(LWC).
To understand this scenario, I have taken Account as a parent object and contact as a child object and in the Lightning Data table we would display few Account fields along with No of Contacts
Please check the full code below
Apex Class
public class LightningDataExampleController {
@AuraEnabled
public static List getAccounts(){
return [SELECT Id, Name, AccountNumber, Site,
(SELECT Id FROM Contacts)
FROM Account
LIMIT 5];
}
}
lightningDataTableExample.html
<template>
<lightning-card title="Lightning Data Table">
<div class="slds-grid slds-no-flex slds-var-p-around_medium ">
<div class="slds-col slds-size_12-of-12">
<lightning-datatable key-field="Id"
data={accounts}
columns={columns}
hide-checkbox-column
>
</lightning-datatable>
</div>
</div>
</lightning-card>
</template>
lightningDataTableExample.js
import { LightningElement } from 'lwc';
import getAccounts from '@salesforce/apex/LightningDataExampleController.getAccounts';
export default class LightningDataTableExample extends LightningElement {
columns = [
{label: 'Name', fieldName: 'Name', type: 'text', sortable: false},
{label: 'Account Number', fieldName: 'AccountNumber', type: 'text', sortable: false},
{label: 'Site', fieldName: 'Site', type: 'text', sortable: false},
{label: 'No of Contacts', fieldName: 'noOfContacts', type: 'text', sortable: false},
];
accounts = [];
error;
connectedCallback(){
this.getAccounts();
}
getAccounts(){
getAccounts()
.then(result =>{
result.forEach(element => {
let noOfContacts = 0;
if(element.Contacts){
element.Contacts.forEach(con =>{
noOfContacts++;
})
}
element.noOfContacts = noOfContacts;
});
this.accounts = result;
})
.catch(error =>{
this.error = error;
})
}
}
lightningDataTableExample.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>54.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Please comment below, if you guys have any quesiton. I'll be happy to answer. Thanks!
Related PostsAdd Delete rows dynamically in Lightning Data Table in LWC Salesforce