function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
StephenDicksonStephenDickson 

How to pass recordId to an Apex method (in a controller) from LWC

Hi All,

I have been attempting to create a button in a LWC that when clicked would pass the current recordId to a method in an existing controller class.  This method fires other methods, all using the recordId as a parameter.  What am I doing wrong?

Apex method:
@AuraEnabled(cacheable=true)
    public static list<Task> generateRDLAndReturnTaskList(id recordId){
        String objectName = recordId.getSObjectType().getDescribe().getName();
        Required_Documents_List_Controller.generateRDL_AuraEnabled(objectName, (String)recordId);
        list<Task> myReturnList = new list<Task>();
        myReturnList = RDL_Lightning_Component_Controller.checkForRDL(recordId);
               
        return myReturnList;
    }

Javascript:
import { LightningElement, api, wire, track} from 'lwc';
import generateRDLAndReturnTaskList from '@salesforce/apex/RDL_Lightning_Component_Controller.generateRDLAndReturnTaskList';

export default class RequiredDocumentList_LWC extends LightningElement {
    @api recordId;
    @track error;
    @track myReturnList


    handleNewClick() {
        generateRDLAndReturnTaskList($recordId)
            .then(result => {
                this.myReturnList = result;
            })
            .catch(error => {
                this.error = error;
            });
    }
}

HTML:
<template>

    <div class="slds-m-around_medium">
        <h1 class="slds-text-heading_small">Required Documents List</h1>
    </div>

    <div class="c-container">
            <lightning-layout>
                <lightning-layout-item padding="around-small">
                        <lightning-layout-item padding="around-small">
                                    <lightning-button
                                        label="Generate RDL"
                                        onclick={handleNewClick}>
                                    </lightning-button>
                        </lightning-layout-item>
                </lightning-layout-item>
            </lightning-layout>
        </div>

</template>

​​​​​​​
David Zhu 🔥David Zhu 🔥
You may change your code a bit in js controller:
generateRDLAndReturnTaskList({recordId: this.recordId}).then(() => {

The first recordId is the parameter name of Apex method generateRDLAndReturnTaskList. the second recordId is the variable recordId in LWC.