@api recordId property in lighting component will give you record id of current record page .
For example – if your using custom lighting component on account record page then using @api recordId you can get record id of current account record in your LWC .
Now in order to send that recordId to apex class follow me :
Here I am assuming that your having the lightning component and apex class with method ,where your trying to send current recordId from lighting component .
Sample APEX method
@AuraEnabled(cacheable = true)
public static void getCurentRecordId(String recordId){
System.debug('recordid '+ recordId)
}
Now import this method and declare @api recordId into your lighting component .
Here is code of LWC JavaScript file , where we call that getCurentRecordId method into connectedCallback which will send recordId to our apex method.
Sample LWC JavaScript Code
import { LightningElement } from 'lwc';
import {api , track } from 'lwc'
import getCurentRecordId from '@salesforce/apex/GetRecordId.getCurentRecordId'
export default class GetRecordID extends LightningElement {
@api recordId;
@track currentRecordid = '';
connectedCallback() {
this.currentRecordid = this.recordId;
curentRecordId(recordId : this.currentRecordid)
.then((result) => {
if (result) {
console.log('Yo yo....found')
} else {
console.log('opps something is wrong')
}
}).catch((error) => {
console.log('Catch Error')
});
}
}
this how simple it is to send current record page Id your apex method , hope we help you to solve your issue , if you have any question and feel to ask , we are happy to help you.
Thank you…..
Mistakes in the code above
- The JavaScript imports
getCurentRecordIdbut callscurentRecordId(...), a different name. - The call is written as
(recordId : value). It must be an object:{ recordId: value }. - The Apex method is marked
cacheable=truebut returnsvoid. A cacheable method must return a value. - The Apex line
System.debug(...)has no semicolon.
Corrected Apex
public with sharing class GetRecordId {
@AuraEnabled(cacheable=true)
public static String getCurrentRecordId(Id recordId) {
System.debug('recordId ' + recordId);
return recordId;
}
}Corrected JavaScript
import { LightningElement, api, wire } from 'lwc';
import getCurrentRecordId from '@salesforce/apex/GetRecordId.getCurrentRecordId';
export default class GetRecordId extends LightningElement {
@api recordId;
@wire(getCurrentRecordId, { recordId: '$recordId' })
wiredResult({ data, error }) {
if (data) {
console.log('Record Id received in Apex: ', data);
} else if (error) {
console.error(error);
}
}
}The $ before recordId makes the wire wait until the page provides the Id. The component receives recordId automatically when it is placed on a record page.
FAQ
How do I get the record Id inside a Visualforce controller?
Use ApexPages.currentPage().getParameters().get('id').
Why is recordId undefined sometimes?
It is set only on record pages and in quick actions. On a home or app page there is no record.