Sub topic 1
What @AuraEnabled Does and Why Components Need It
Prerequisites
Assume you know basic Apex classes, methods, SOQL, and Lightning Web Component (LWC) JavaScript. You should also know that a component runs in the browser while Apex runs on Salesforce servers.
What `@AuraEnabled` Does
@AuraEnabled is an Apex annotation that exposes a method or property to Lightning components. Without it, an Apex method remains server-side code that an LWC or Aura component cannot call through the Salesforce client framework.
A controller method usually has this shape:
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
];
}
}The component imports this method by its Apex class and method name. The annotation creates the boundary between client code and server code.
Rules for AuraEnabled Methods
An exposed method must meet these requirements:
- It is
static. - It is
publicorglobal. - It has the
@AuraEnabledannotation. - Its parameters and return value use types supported by the Lightning platform.
- It is not overloaded. Give each exposed method a unique name.
Use with sharing on the controller when the method should respect the caller's record-sharing rules. Also enforce object and field permissions, such as with WITH USER_MODE, rather than assuming that the annotation provides security.
Passing Parameters and Returning Data
A component passes arguments by parameter name. Apex can receive primitives, record IDs, sObjects, and collections when the types are supported. Return only the data the component needs.
A read method commonly uses cacheable=true. This declares that the method does not perform DML and allows the result to be cached. Methods that insert, update, or delete records must omit cacheable=true.
Returning Structured Data with Wrapper Classes
When a response combines values from multiple sources, define an inner wrapper class. Mark every property sent to the component with @AuraEnabled.
public class Summary {
@AuraEnabled public String name;
@AuraEnabled public Integer contactCount;
}The client receives a JavaScript object with name and contactCount, rather than an entire Salesforce record.
Exercise
Why must each wrapper property be annotated?
Show answer
Only annotated properties are serialized and sent to the Lightning component.