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. 


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



Post a Comment

10 Comments

  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.

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

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

      Delete
  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

    ReplyDelete
    Replies
    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?

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

      Delete
  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?

    APEX-----------
    public with sharing class OpportunityController
    {
    public OpportunityController()
    {

    }

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


    HTML-------------

















    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
    {

    handleCancel(_event)
    {
    // 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})
    {
    if(data)
    {
    this.opportunities = data;
    this.error = undefined;
    }else
    {
    this.error = error;
    this.opportunities = undefined;
    }
    }

    }

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



    52.0
    true


    lightning__RecordAction




    ScreenAction





    ReplyDelete
    Replies
    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.

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

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

      Delete