0

I want to retrieve records from apex based on an Id value from a lookup field on an object. getRecord() works for getting the deptId value to display in HTML, but when I try to use the variable as an apex parameter it doesn't work.

If I use a hardcoded Id value (a181F000000i6vPQAQ) the apex returns the correct results. How do I properly replace it with the deptId from getRecord() ?

JS:

import { LightningElement, api, track, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import DEPARTMENT_LOOKUP_FIELD from '@salesforce/schema/Job_Description__c.Department_Lookup__c';

const FIELDS = [
   DEPARTMENT_LOOKUP_FIELD,
];

export default class JobDescriptionContainer extends LightningElement {
    @api recordId; 
    @track aorsForDept = [];

    @wire(getRecord, {recordId: '$recordId', fields: FIELDS })
    jobDescription;

    get deptId() {
        return getFieldValue(this.jobDescription.data, DEPARTMENT_LOOKUP_FIELD);
    }

    @wire(getAORsForDept, {deptId: '$deptId'})
    wiredAORsForDept({error, data}) {
        if (data) {
            this.aorsForDept = data;
            this.error = undefined;
        } else if (error) {
            this.aorsForDept = undefined;
            this.error = error;
        }
    }

Apex:

    @AuraEnabled(cacheable=true)
    public static AOR__c[] getAORsForDept(string deptId) {
        return [
            SELECT
                Id,
                Name, 
                Applies_To__c,
                Department__c,
                Department__r.Name
            FROM AOR__c
            WHERE Department__r.Id =: deptId
        ];
    }  
2
  • 2
    What does "it doesn't work" mean? Mar 28, 2020 at 1:17
  • 3
    Also, there are several problems with your code. Are you sure you copied everything here? Mar 28, 2020 at 1:18

1 Answer 1

1

I would suggest the following change to make this work:

/**
 * Provide a tracked property to allow reactive use in the template or wire
 * invocations.
 *
 * @type {String}
 */
@track deptId;

@wire(getRecord, { recordId: '$recordId', fields: FIELDS })
receiveJobDescription({ error, data }) {
    if (error) {
        // TODO handle error
    } else if (data) {
        this.deptId = getFieldValue(data, DEPARTMENT_LOOKUP_FIELD);
    }
}

@wire(getAORsForDept, { deptId: '$deptId' })
wiredAORsForDept({ error, data }) {
    ...

NB: Not saying there aren't other issues, but I think this will address the primary one.

You must log in to answer this question.

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