0

I am using a lightning-tree-grid to display accounts with related contacts but cannot display the contacts associated with the accounts. What could be the problem?

HTML:

<template>
    <lightning-card title="Accounts and related contacts">
        <lightning-tree-grid columns={columns}
                             data={data}
                             key-field="Id">
        </lightning-tree-grid>
    </lightning-card>
</template>

JS:

    import { LightningElement, track } from 'lwc';
    import getAccountWithRelatedContacts from '@salesforce/apex/GridController.getAccountWithRelatedContacts';

    export default class LightningGridComponent extends LightningElement {

    // accounts;
    data;
    error;

    connectedCallback(){
        this.getAccountWithRelatedContacts();
    }

    @track columns= [{label : 'Name', fieldName : 'Name'},
                      {label : 'First Name', fieldName : 'FirstName'},
                      {label : 'Last Name', fieldName : 'LastName'},
                      {label : 'Email', fieldName : 'Email'}
                    ];
    
    getAccountWithRelatedContacts() {
        getAccountWithRelatedContacts()
            .then(result => {
                const accounts = JSON.parse(JSON.stringify(result));
                console.log(accounts);
                for(var i =0; i< accounts.length; i++){
                    var relatedContacts = accounts[i]['Contacts'];
                    if(relatedContacts){
                        accounts[i].__children = relatedContacts;
                        delete accounts[i].Contacts;
                    }
                }
                this.data = accounts;
            })
            .catch(error => {
                this.error = error.body.message;
                console.log('*******Error****** ' + this.error);
            });
    }
}

Apex class:

public with sharing class GridController {
@AuraEnabled
public static List<Account> getAccountWithRelatedContacts(){
    try {
        return [SELECT Id, Name, (SELECT FirstName, LastName, Email FROM Contacts) FROM Account LIMIT 10];
    } catch (Exception e) {
        throw new AuraHandledException(e.getMessage());
    }
}
}

1 Answer 1

1

It's _children, not __children. It's important to check the documentation when something isn't working, as it's easy to make mistakes like this.

1
  • noted @sfdcfox :)
    – code234
    Commented Jun 25 at 19:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .