What I am looking to achieve is for a component on a Lightning record page to take the ID of the record in context, get the value of a field upon that record, then feed that into an Apex method to return a list of records to display within that component.
Let's say that I have some object that has a lookup to Account. What I want to do is have a Lightning record page for that object that will show me the Contacts for the Account in that lookup field.
My efforts so far have not produced positive results. Here's a flavour of what I have:
Apex
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [SELECT Id FROM Contact WHERE AccountId = :accountId];
}
LWC Javascript
import { LightningElement, api, wire, track } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import getContacts from '@salesforce/apex/Contacts.getContacts';
import ACCOUNT_ID from '@salesforce/schema/CustomObject__c.Account__c';
export default class ShowContacts extends LightningElement {
@track foundContacts;
@api recordId;
@wire(getRecord, { recordId: '$recordId', fields: [ ACCOUNT_ID ] })
account;
@wire(getContacts, { accountId: this.accountId() })
contacts({ error, data }) {
if (data) {
this.foundContacts = data;
this.error = undefined;
}
else {
this.error = error;
this.foundContacts = undefined;
}
}
get accountId() {
return getFieldValue(this.account.data, ACCOUNT_ID);
}
}
UPDATE:
I managed to get around this by removing the whole concept of getting the Account ID within the component, and doing that step within the Apex class at the expense of 1 more SOQL query, but it would be great if I could achieve that all within the component.
Is it impossible to retrieve a value from a referenced record and pass that into an Apex call in Lightning Web Components?