Monday, June 17, 2019

How to display Reference(Parent) Fields Data in Datatable in Lightning Component

By default, the lightning data table shows the current record data, it will not display parent record data.
Ex: Account.Owner.Name

This post explains how to display reference(Parent) fields data in the lightning data table

In this example, I am querying the opportunity data along with Account related data and Owner related data.

<aura:component controller="LWCExampleController" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    <aura:attribute name="data" type="List" />
    <aura:attribute name="columns" type="List"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <lightning:card title="Showing Reference Fileds Data in Lightning Datatable">
        <lightning:datatable data="{!}"

    doInit : function(component, event, helper) {
        component.set('v.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'}
        // getting Opportunity data from server
        var action = component.get("c.retriveOpportunities");
            // set parameters if any 
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var rows = response.getReturnValue();
                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];
                    // checking if any account related data in row
                    if (row.Account) {
                        row.AccountName = row.Account.Name;
                        row.AccountOwner = row.Account.Owner.Name;
                    // checking if any owner related data in row
                    if(row.Owner) {
                        row.OpportunityOwner = row.Owner.Name;
                    // formatting created date 
                    row.CreatedDate = $A.localizationService.formatDate(row.CreatedDate, "MMMM DD YYYY, hh:mm:ss a")
                // setting formatted data to the datatable
                component.set("", rows);

public inherited sharing class LWCExampleController {
    public static list<Opportunity> retriveOpportunities() {
        return [SELECT Id, Name, Account.Name,, Owner.Name, CreatedDate FROM Opportunity LIMIT 10];


1 comment:

  1. Hi, I tried doing this but even in console I am able to see the values it doesn't show any data in the datatable and if I remove this parent field thing that it shows the data correctly. Any idea why this would be happening?