Sub topic 1
Exposing an Apex Method with `@AuraEnabled`
Prerequisites
This chapter assumes basic JavaScript, including modules, objects, and Promises. You should also know LWC templates and event handlers, basic Apex and SOQL, and how to deploy code to a Salesforce org.
Exposing an Apex Method with `@AuraEnabled`
An Apex method is a server-side operation. To make it callable from an LWC, add the @AuraEnabled annotation. The method must be public or global, and it must be static.
public with sharing class ContactController {
@AuraEnabled
public static List<Contact> searchContacts(String searchTerm) {
String key = '%' + searchTerm + '%';
return [
SELECT Id, Name, Email
FROM Contact
WHERE Name LIKE :key
WITH USER_MODE
ORDER BY Name
LIMIT 20
];
}
}with sharing applies the running user's record-sharing rules. WITH USER_MODE applies object and field permissions to the query. These choices help prevent the controller from exposing data the user cannot access.
Importing the Apex Method into Your Component
Import the method using its Apex class and method name. Salesforce generates a JavaScript function for this import.
import { LightningElement } from 'lwc';
import searchContacts from '@salesforce/apex/ContactController.searchContacts';
export default class ContactSearch extends LightningElement {
searchTerm = '';
contacts = [];
handleTermChange(event) {
this.searchTerm = event.target.value;
}
}The imported function does not run during import. It runs when your component calls it.
Calling the Method Imperatively
An imperative call is a direct call that your code starts, such as after a button click. It returns a Promise, which represents a value that will be available later.
async handleSearch() {
this.contacts = await searchContacts({
searchTerm: this.searchTerm
});
}The async keyword allows await to pause this method until Apex returns. In production code, use try and catch so a server error does not become an unhandled rejection.
Passing Parameters
Pass one object to the imported function. Each property name must match an Apex parameter name exactly.
searchContacts({ searchTerm: this.searchTerm })For multiple parameters, include multiple properties:
saveContact({ contactId: this.contactId, email: this.email })Exercise
What JavaScript object should you pass to an Apex method declared as searchContacts(String searchTerm)?
Show answer
Pass { searchTerm: value }, where value is the search text.