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

13 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
  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

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

    ------------
    JS
    ------------
    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}){
    if(data){
    this.leads = data;
    alert('Lead Record'+JSON.stringify(this.leads));
    this.error = undefined;
    }else{
    this.error = error;
    this.leads = undefined;
    }
    }
    -----------
    HTML
    ----------







    -------------
    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();
    con.LastName=ac.Name;
    con.AccountId=ac.id;
    conList.add(con);
    Opportunity opp = new Opportunity();
    opp.Name=ac.Name;
    opp.AccountId=ac.id;
    opp.CloseDate=system.today();
    opp.StageName='Prospecting';
    oppList.add(opp);
    }
    if(conList.size()>0)
    Insert conList;
    if(oppList.size()>0)
    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];
    }
    @AuraEnabled(Cacheable=true)
    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')
    leadIds.add(led.id);
    }
    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;
    accList.add(ac);

    }
    if(accList.size()>0)
    Insert accList;
    createAccountContact(accList,updatedleadrecs);

    }
    }

    ReplyDelete
    Replies
    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 https://www.codekiat.com/2022/06/how-to-debug-lightning-web-components-in-salesforce.html

      share if any error in the apex.

      Delete