Get parent record fields using getRecord uiRecordApi in lwc

lightninglightning-web-componentslwc-wire-adapterschema

I'm trying to get parent record value using uiRecordApi in my lwc component.
But I'm getting error.

Cannot read property 'value' of undefined

import OPPORTUNITY_ISCLOSED from '@salesforce/schema/Opportunity.Name';
import OPPORTUNITY_ID from '@salesforce/schema/Opportunity.Id';
import ACCOUNT_OWNER from '@salesforce/schema/Opportunity.Account.OwnerId';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';

const fields = [OPPORTUNITY_NAME,OPPORTUNITY_CLOSEDATE,OPPORTUNITY_ISCLOSED,OPPORTUNITY_ID,ACCOUNT_OWNER];

export default class ShowParentFields extends LightningElement {
    
    @wire(getRecord, { recordId: '$recordId', fields })
record({ error, data }) {
    if (data) {
        console.log('>>> Name... '+data.fields.Name.value);
        console.log('>> Account Owner... '+data.fields.Account.OwnerId.value);
    }
    }
}

In console log, I can see the name value correctly, but while accessing Account Owner I'm getting undefined.

Best Answer

you have to use getFieldValue in order to get parent field values

import OPPORTUNITY_NAME from '@salesforce/schema/Opportunity.Name';
import OPPORTUNITY_ID from '@salesforce/schema/Opportunity.Id';
import ACCOUNT_OWNER from '@salesforce/schema/Opportunity.Account.OwnerId';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';

const fields = [OPPORTUNITY_NAME,OPPORTUNITY_CLOSEDATE,OPPORTUNITY_ISCLOSED,OPPORTUNITY_ID,ACCOUNT_OWNER];

export default class ShowParentFields extends LightningElement {
    
    @wire(getRecord, { recordId: '$recordId', fields }) record({ error, data }){
        if (data) {
            console.log('>>> Name... ' + getFieldValue(data, OPPORTUNITY_NAME));
            console.log('>> Account Owner...' + getFieldValue(data, ACCOUNT_OWNER);
        }
    }
}

take a look at the getFieldValue documentation. Here is a good example to follow.

Related Topic