2

I'm new to Salesforce.

How to pass recordId to Apex Method from LWC. I tried no luck. Please help on this.

.js

import { LightningElement, api, track, wire } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import Enroll from '@salesforce/apex/EnrollmentController.Enroll';
import { getRecord } from 'lightning/uiRecordApi';

export default class CreateFamilies extends LightningElement {
@track openmodel = false;
@api recordId;   

@wire(getRecord, {
    recordId: '$recordId' })
enrolment__c;  

openmodal() {
    this.openmodel = true
}

closeModal() {
    this.openmodel = false
} 

saveMethod() { 
    //alert('save method invoked');
    Enroll({
      //  enrolid: '0012w000003YituAAC'
          enrolid: recordId
    })

    const showSuccess = new ShowToastEvent({
        title: 'Success!',
        message: 'Sucessfully Enrolled',
        variant: 'Success',
    });

    this.dispatchEvent(showSuccess);
    this.closeModal();
}
}

Apex Class:

public with sharing class  EnrollmentController {

@AuraEnabled
public static void Enroll(id enrolid) {

    system.debug('Id ' + enrolid);

}
}
0

1 Answer 1

9

When you have an LWC that works in Lightning Record Pages, it can automatically receive the record ID by declaring an API property:

@api
recordId;

The LWC framework ensures this gets set when the LWC is in the Lightning Record Page (there are some extras to apply in community use).

This is all covered in the documentation.

On top of this, there are specific rules for how to use such a value. For example, the use of '$recordId' when wanting to send it as a property value in the parameters of a wire is called a "reactive variable" and is covered here.

Finally, whenever you want to use a property of your LWC in functions within your LWC you must remember to scope them to the LWC instance, via use of the "this" variable. So using "recordId" in a function (unless it is a parameter to that function explicitly) doesn't work while using "this.recordId" does.

Update your code to:

Enroll({
      enrolid: this.recordId
}).then(...

(You'll want to add the imperative method call promise handling using then and error, with the "successful enrolment" toast being created from the "then" handler function and some error message being shown in the "error" handler function.)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .