Sub topic 2
Rules for AuraEnabled methods
This chapter assumes you can write basic Apex (classes, static methods, SOQL, DML) and a simple Lightning web component with decorators such as @api and @wire. It also assumes you know how to read a record ID.
The previous chapter covered what @AuraEnabled does. This chapter covers the rules a method must follow so a component can call it. Most of these rules are not enforced when you save the class. A method that breaks them often compiles and then fails when a component calls it. Knowing the rules saves you from debugging those runtime failures.
The rules at a glance
| Rule | What to do | What happens if you break it |
|---|---|---|
| Method is `static` | Declare controller methods `static` | The component cannot call the method |
| Access is `public` or `global` | Use `public` for org code, `global` only for managed packages | The component cannot see the method |
| Class is visible to the caller | Make the class `public` or `global` and grant the user class access | Runtime access error |
| No overloading | Give each method a unique name | Runtime error, or the wrong method runs |
| `cacheable=true` means no DML | Keep cacheable methods read-only | Runtime error when the method runs |
| Parameter names match | Use the Apex parameter names as JavaScript object keys | The parameter arrives as `null` |
The sections below explain each rule.
Static methods
Every method that a Lightning web component calls must be static. Lightning does not create an instance of your class for each call. It calls the method on the class itself. An instance method has no object to run on, so the platform cannot invoke it.
The same reasoning explains a related point. Each call from a component is a separate server request with its own transaction. Static variables are reset on every request, so you cannot use them to keep state between calls. If a component needs state across calls, hold it in JavaScript properties and send it back as parameters.
Access modifiers
Mark controller methods public or global. Use public for code in your own org. Use global only when the method is part of a managed package and must be visible outside the package namespace. A private or protected method is not callable from a component.
The class needs the right visibility too. Declare the class public or global, not private. Separately, the running user needs access to the class. Class access is granted through a profile or a permission set. If a user lacks it, the call fails even though the code is correct. This is a frequent cause of "works for me, fails for the user" reports, because administrators often have broad access that other users do not.
The annotation goes on the method
Put @AuraEnabled on each method you want to expose, not on the class. Methods without the annotation stay hidden from components, even in the same class. This makes it easy to keep helper methods private to the controller.
public with sharing class AccountSearchController {
@AuraEnabled(cacheable=true)
public static List<Account> searchAccounts(String searchTerm) {
if (String.isBlank(searchTerm)) {
return new List<Account>();
}
String pattern = '%' + searchTerm + '%';
return [
SELECT Id, Name, Industry
FROM Account
WHERE Name LIKE :pattern
WITH USER_MODE
ORDER BY Name
LIMIT 25
];
}
@AuraEnabled(cacheable=true)
public static List<Account> getAccountsByIndustry(String industry) {
return [
SELECT Id, Name, Industry
FROM Account
WHERE Industry = :industry
WITH USER_MODE
ORDER BY Name
LIMIT 25
];
}
// Not annotated: components cannot call this method.
private static String buildPattern(String term) {
return '%' + term + '%';
}
}The class is with sharing, so queries respect record visibility. The queries also use WITH USER_MODE, which enforces the user's object and field permissions. A later chapter covers both in depth.
Do not overload methods
Apex normally lets you define several methods with the same name and different parameters. Do not do this with @AuraEnabled methods. The framework identifies a method by its class and name, not its signature. Two methods with the same name give it no way to tell which one you mean.
The two methods in the previous example show the correct approach. They do similar work, so a developer might be tempted to name both getAccounts. Instead they have different names, searchAccounts and getAccountsByIndustry, and each is imported separately.
import searchAccounts from '@salesforce/apex/AccountSearchController.searchAccounts';
import getAccountsByIndustry from '@salesforce/apex/AccountSearchController.getAccountsByIndustry';The import path has the form @salesforce/apex/ClassName.methodName. If your code is in a namespace, the path is @salesforce/apex/namespace.ClassName.methodName. The name after the last dot is the only thing that picks the method, which is why it must be unique.
Parameters are matched by name
When a component calls a method, it passes one JavaScript object. Each key in that object must match an Apex parameter name exactly, including case. Order does not matter, and there are no positional arguments.
Here is a component that calls searchAccounts. The key searchTerm matches the Apex parameter searchTerm.
import { LightningElement, wire } from 'lwc';
import searchAccounts from '@salesforce/apex/AccountSearchController.searchAccounts';
export default class AccountSearch extends LightningElement {
term = '';
@wire(searchAccounts, { searchTerm: '$term' })
accounts;
handleInput(event) {
this.term = event.target.value;
}
}<template>
<lightning-input label="Search accounts" onchange={handleInput}></lightning-input>
<template lwc:if={accounts.data}>
<template for:each={accounts.data} for:item="acc">
<p key={acc.Id}>{acc.Name}</p>
</template>
</template>
</template>If you misspell the key, for example { term: '$term' }, nothing fails at compile time. The Apex method runs with searchTerm equal to null. That is why searchAccounts checks String.isBlank first and returns an empty list. Treat every parameter as possibly null or empty, because the client controls what arrives.
A parameter that is missing from the JavaScript object arrives as null. A parameter that the Apex method does not declare is ignored.
Cacheable methods must be read-only
Setting cacheable=true tells the platform that the result can be stored on the client and reused. This is required for @wire, and it makes repeat reads faster. The cost is a restriction: a cacheable method must not change data. If a cacheable method performs DML, the call fails at runtime.
The reason is that cached results can be served without reaching the server at all. A method that writes data would silently skip the write on a cache hit. The platform prevents that case.
The next class shows the correct split. Reads are cacheable and the write is not.
public with sharing class AccountEditController {
@AuraEnabled(cacheable=true)
public static Account getAccount(Id accountId) {
return [
SELECT Id, Name, Industry
FROM Account
WHERE Id = :accountId
WITH USER_MODE
LIMIT 1
];
}
@AuraEnabled
public static void updateIndustry(Id accountId, String industry) {
Account acc = new Account(Id = accountId, Industry = industry);
update as user acc;
}
}getAccount is safe to wire. updateIndustry has no cacheable setting, so it defaults to non-cacheable, and a component can only call it imperatively. A later chapter covers imperative calls.
Putting the checks in order
When a call fails, work through the rules in a fixed order. This diagram shows one useful order.
Common mistakes
The following snippet breaks three rules at once. It compiles, so the problems appear only when a component calls it.
public with sharing class BrokenController {
// Instance method: no object exists for the platform to call it on.
@AuraEnabled
public Account getAccount(Id accountId) {
return [SELECT Id, Name FROM Account WHERE Id = :accountId LIMIT 1];
}
// Overloaded name: the two methods below are ambiguous to the framework.
@AuraEnabled
public static List<Account> find(String name) {
return [SELECT Id FROM Account WHERE Name = :name];
}
@AuraEnabled
public static List<Account> find(String name, String industry) {
return [SELECT Id FROM Account WHERE Name = :name AND Industry = :industry];
}
// DML in a cacheable method: fails when it runs.
@AuraEnabled(cacheable=true)
public static void rename(Id accountId, String newName) {
update new Account(Id = accountId, Name = newName);
}
}Fix them in this way:
- Add
statictogetAccount. - Rename the two
findmethods, for examplefindByNameandfindByNameAndIndustry. - Remove
cacheable=truefromrename, because it writes data. A write method also needs avoidor data return that the caller can use, andrenamealready meets that.
Summary of the rules
A component-callable Apex method is static, public or global, in an accessible class, uniquely named, annotated with @AuraEnabled, and called with a parameter object whose keys match the Apex parameter names. Add cacheable=true only when the method is read-only. The next chapters build on this base: what types can be passed in and returned, how wrapper classes shape data, and how cacheable methods behave with @wire.
Exercise
A developer writes two methods in one controller, both annotated with @AuraEnabled: public static List<Contact> getContacts(Id accountId) and public static List<Contact> getContacts(Id accountId, String lastName). The class saves without errors, but the component calling getContacts behaves unpredictably. What is wrong, and how do you fix it? Also, a component passes { acctId: this.recordId } to a method declared as getContacts(Id accountId). What value does accountId have in Apex?
Show answer
The two methods overload the same name, and @AuraEnabled methods must not be overloaded, because the framework identifies a method by class and name only. Rename them, for example getContacts and getContactsByLastName, and import each one separately. The JavaScript key acctId does not match the Apex parameter name accountId, so accountId is null in Apex. Change the key to accountId.