Ad Code

How to pass record id from lightning web component to apex controller

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. 


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

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.


import { LightningElement, track, wire, api } from 'lwc';
import getContactsRelatedToAccount from 
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}){
            this.contacts = data;
            this.error = undefined;
            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 


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="">

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.


public class LwcController {
    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.


Pass record id to apex controller

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


Post a Comment


  1. Hi Naveen i copied the code as is and i dont see the accid passed to the class, can you double check or do i need to enable any permissions for LWC? this is my/org first LWC.

    1. Thanks for highlighting, I have updated with the latest version of working code, please test and let me know if any issues.

    2. and also please make sure the component is added to the account record page.

  2. Hi, I want to show contacts of an one particular Account , for that I have created LWC and Calling apex method using wire property. while calling apex method using wire I am passing by a custom label which I created to store that accountId. But the method is not getting called and not displaying records in UI, can please giive some inputes on this.
    Any help much appreciated, thanks in advance

    1. is it custom label or custom variable you are trying with? and Can you add the debug statements in the apex to check if it is passing account id?

    2. share the code, so that we can give added inputs.

  3. Hi Naveen,
    I want to display the related opportunities of an account using quick action button.
    I am using above code for oppty but its not working.
    can you help me on this?

    public with sharing class OpportunityController
    public OpportunityController()


    public static List getOpportunities(String strAccId)
    return [SELECT Id, Name, StageName, CloseDate, AccountId FROM Opportunity WHERE AccountId =: strAccId];
    catch (Exception e)
    throw new AuraHandledException(e.getMessage());


    JS ------------------

    import { LightningElement, api, wire, track} from 'lwc';

    import getOpportunityList from '@salesforce/apex/OpportunityController.getOpportunities';

    import { CloseActionScreenEvent } from 'lightning/actions';

    export default class AccQuickActionForOppty extends LightningElement

    // Add your cancel button implementation here
    this.dispatchEvent(new CloseActionScreenEvent());

    @api recordId ;
    @track opportunities;

    @track columns = [
    { label: 'Opportunity Name', fieldName: 'Name', type: 'text' },
    { label: 'Stage Name', fieldName: 'StageName', type: 'text' },
    { label: 'Close Date', fieldName: 'CloseDate', type: 'date' }

    @wire(getOpportunityList, { strAccId: '$recordId' })
    wiredOpportunityRecords({error, data})
    this.opportunities = data;
    this.error = undefined;
    this.error = error;
    this.opportunities = undefined;


    Meta XML----------




    1. I have tried this code in my developer org.

      Just replaced return type in the apex method from List to List and it is working as expected. Please note, I have tried this by directly displaying component in the screen load not from quick action.

      Please try again and let me know if you face any issues. and also include exact error.

      Thank you.

  4. i want to display account record related list to show the all related record on 1 account.. how to do

    1. Question is not clear. Could you please add more details. Thanks.

  5. How can I Hide lightning-card tag if their is no releted contacts?
    i tried if:true={contacts} but its not hiding the card and column name

  6. Hi Naveen,
    I want to convert lead by using quick action by sending the recordId from LWC to apex, using apex i want to create account, contact, opportunity.
    But i am unable to convert the lead.,

    Can please check my code and let me know the corrections.

    import { LightningElement, wire,track,api} from 'lwc';
    import leadConcersionTrigger from '@salesforce/apex/LeadTriggerHandler.leadConcersionTrigger';
    export default class Leadconversion extends LightningElement {

    @api recordId;
    @track leads;
    @track columns = [
    { label: 'Last Name', fieldName: 'Name', type: 'text' },
    { label: 'Company', fieldName: 'Company', type: 'text' },


    @wire(leadConcersionTrigger, {leadId: '$recordId'})
    WireLeadRecords({error, data}){
    this.leads = data;
    alert('Lead Record'+JSON.stringify(this.leads));
    this.error = undefined;
    this.error = error;
    this.leads = undefined;

    Apex Class
    public class LeadTriggerHandler {
    public static List createAccountContact(List accountList, List leadrecs){
    List conList = new List();
    List oppList = new List();
    for (Account ac:accountList){
    Contact con = new Contact();
    Opportunity opp = new Opportunity();
    Insert conList;
    Insert oppList;
    return leadrecs;
    //Delete [Select id FROM lead where Id IN:leadIds];
    //List deletelds = [Select id FROM lead where Id IN:leadIds ALL ROWS];
    public static void leadConcersionTrigger(String leadId){
    List leadrec = [Select id, name from lead where Id =: leadId];
    Set leadIds = new Set();
    for(lead led :leadrec ){
    If(led.Status=='Responsive – Interested')
    List updatedleadrecs = [Select id,Name FROM Lead where Id IN:leadIds];
    List accList = new List();
    for (lead ld:updatedleadrecs){
    Account ac = new Account ();
    ac.Name = ld.Name;

    Insert accList;


    1. Could you please share HTML Code of LWC as well? Check if you are getting the record Id in the Apex. Debug your lwc using the steps mentioned here

      share if any error in the apex.