[SalesForce] LWC: Pass a record field as a parameter to apex

I wish to query for parent record data (which is a lookup). How do I pass a parameter to the apex class that is not the '$recordId'?

Apex class:

public with sharing class cc_CaseOrderController {
    public static Order getOrder(String salesOrder) {
        return [SELECT Id FROM Order WHERE Id = :salesOrder];


import { LightningElement, wire, api } from 'lwc';
import getOrder from '@salesforce/apex/cc_CaseOrderController.getOrder';
import SALES_ORDER_FIELD from '@salesforce/schema/Case.Sales_Order__c';

export default class OrderCaseViz extends LightningElement {
    @api recordId;
    @wire (getOrder, {salesOrder: SALES_ORDER_FIELD}) cases; // this cant be done?

Whats the way forward to pass the SALES_ORDER_FIELD to my apex class and have the Order returned so I can render it on an AppPage?

Best Answer

Summarizing my comments as an answer with sample code snippet.

SALES_ORDER_FIELD represents the field name (not the value) and hence, cannot be used this way. Pass the case record ID (recordId) to the apex method and let the apex method query for the parent record ID or the parent record field values.

In the LWC JS file, code for this wire service call should be something like this:

parentOrderStatus; // private field to store the case order status

@wire(caseData, {recordId: '$recordId'})
caseinfo(error, data){
       this.parentOrderStatus = result.data.Sales_Order__r.Status__c;
   else if(error){
       this.error = error;

Bind parentOrderStatus directly in the template HTML (or you could also make use of a getter property). Note that the wire service may get triggered more than once during the component lifecycle and hence, if you use {caseinfo.Sales_Order__r.Status__c} directly on the template, you might run into undefined JS errors (causing the component to crash).

Note: This is only a sample assuming that you are returning a single sobject from the apex method. So, if you were to return a List, this code would need to be updated. Also, in the wired function, handle the error accordingly so that there is some graceful indication in the template.

Related Topic