Pass record id to apex controller in salesforce

In this blog post, we have mentioned detailed steps to pass the account record id from the lightning web component to the server-side apex controller and display related contacts in the user interface. Create a new lightning web component with the details mentioned below and let us know if you encounter any issues in implementing this functionality. 


accountRelatedContacts.html

<template>
    <lightning-card title="LWC Record Id Example ">
        <lightning-datatable data={contacts} columns={columns} key-field="Id">
        </lightning-datatable>
    </lightning-card>
</template>

Template code renders user interface displaying records retrieved from the apex controller. Lighting-datatable is a base component used to display the records in the table format without writing an extra HTML code for the table rows and columns.


accountRelatedContacts.js

import { LightningElement, track, wire, api } from 'lwc';
import getContactsRelatedToAccount from 
'@salesforce/apex/LwcController.getContactsRelatedToAccount';
export default class AccountRelatedContacts extends LightningElement {
    @api recordId;
    @track contacts;
    @track columns = [
        { label: 'First Name', fieldName: 'FirstName', type: 'text' },
        { label: 'Last Name', fieldName: 'LastName', type: 'text' },
        { label: 'Email', fieldName: 'Email'}
    ];

    @wire(getContactsRelatedToAccount, {accId: '$recordId'}) 
    WireContactRecords({error, data}){
        if(data){
            this.contacts = data;
            this.error = undefined;
        }else{
            this.error = error;
            this.contacts = undefined;
        }
    }
}

In the client-side js file, we have initialized the list of columns, apex class, and apex method.

@wire is used to read Salesforce data. Lightning web components use a reactive wire service. When the wire service provisions data, the component re-renders.
We have called getContactsRelatedToAccount method in the apex class LwcContoller.cls to get the contacts. accId is an input parameter to the apex method.

Please note, alternative to wire service we can also use connectedCallback() method to fetch the data from apex 


accountRelatedContacts.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
      </targets>
</LightningComponentBundle>

Meta file in the lightning web component bundle is mandatory and it is a standard file available when we create the new lightning web component. The target element is mentioned to make this component available to required lightning pages.


LwcContoller.cls

public class LwcController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContactsRelatedToAccount(String accId) {
        system.debug('accId >> ' + accId);
        return [SELECT Id, FirstName, LastName, Email, Phone from Contact where AccountId = :accId];
    }
}


@AuraEnabled decorator is mandatory when you call an apex method from the lightning aura or lightning web component.
accId is an input parameter to the method. Query on contact sObject to get the list of contacts based on the account id. The list is immediately returned to the client-side js file and the data is rendered to the user interface.


Result

Pass record id to apex controller


Update:
This code works only in the record pages. In app page or home pages record id will be null.  


ALSO READ