Sub topic 4
Passing parameters
This chapter assumes you can already import an Apex method and call it imperatively from an event handler. It covers how data moves from your component to the Apex method: the shape of the argument, how types are converted, and the mistakes that produce a silent null instead of an error.
The single-object rule
An imported Apex method is a JavaScript function that takes at most one argument: an object. Each key is the name of an Apex parameter, and each value is what that parameter receives.
Here is the controller from the earlier chapters:
public with sharing class ContactController {
@AuraEnabled
public static void updateEmail(Id contactId, String email) {
try {
Contact c = new Contact(Id = contactId, Email = email);
update as user c;
} catch (DmlException e) {
throw new AuraHandledException(e.getDmlMessage(0));
}
}
}The two Apex parameters are contactId and email. The call in JavaScript looks like this:
import { LightningElement, api } from 'lwc';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
export default class EmailEditor extends LightningElement {
@api recordId;
email = '';
handleEmailChange(event) {
this.email = event.target.value;
}
async handleSave() {
try {
await updateEmail({ contactId: this.recordId, email: this.email });
} catch (error) {
console.error(error?.body?.message || error?.message);
}
}
}Two points about this call:
- You do not pass positional arguments.
updateEmail(this.recordId, this.email)does not work. - The order of keys does not matter. Only the names do.
A method with no parameters is called with no argument, as in getAccounts(). Passing {} also works.
Names must match exactly
The platform binds values by name. If the Apex parameter is searchTerm and you send { term: 'Ada' }, the method still runs, but searchTerm is null. A query such as LIKE :key then builds the string %null%, or throws a null reference error, depending on your code. You get wrong results with no clear error.
Check these when a parameter arrives as null:
- The spelling and casing of the key against the Apex signature.
- Whether the value is
undefined. A key with anundefinedvalue is dropped during serialization, so Apex seesnull. - Whether you renamed the Apex parameter and forgot the component.
Apex does not allow overloaded @AuraEnabled methods, so one method name always has one signature.
Type conversion
The values are sent as JSON and converted to Apex types on the server. These mappings cover most cases:
| Apex parameter type | What to send from JavaScript | Notes |
|---|---|---|
| `String` | string | Send `''` or `null` for empty. |
| `Integer`, `Long` | number | Convert input strings first with `Number()`. |
| `Decimal`, `Double` | number | |
| `Boolean` | `true` or `false` | From a checkbox, use `event.target.checked`. |
| `Id` | 15 or 18 character string | An invalid Id raises an error before your method runs. |
| `Date` | `'YYYY-MM-DD'` string | This is what `lightning-input type="date"` gives you. |
| `Datetime` | ISO 8601 string | For example `'2026-11-30T13:31:46.000Z'`. |
| `List<T>`, `Set<T>` | array | Elements follow the same rules as `T`. |
| `Map<String, T>` | plain object | Keys become the map keys. |
| Apex class | object | Properties must be marked `@AuraEnabled`. |
| `SObject` | object with field names as keys | Add `sobjectType` only when the declared type is the generic `SObject`. |
The most common conversion bug comes from form inputs. event.target.value is always a string, even for type="number". Apex converts a numeric string to Integer in many cases, but relying on that hides mistakes. Convert on the JavaScript side and handle the empty case explicitly:
const raw = this.template.querySelector('lightning-input[data-id="max"]').value;
const maxRows = raw === '' || raw == null ? null : Number(raw);Passing a structured request
When a method needs more than three or four inputs, a single Apex class parameter keeps the signature readable and lets you add fields later without changing every caller. You still wrap it in the outer object, keyed by the Apex parameter name.
public with sharing class ContactSearchController {
public class SearchRequest {
@AuraEnabled public String term;
@AuraEnabled public Integer maxRows;
@AuraEnabled public Date createdAfter;
}
@AuraEnabled(cacheable=true)
public static List<Contact> search(SearchRequest request) {
String key = '%' + (request.term == null ? '' : request.term) + '%';
Integer maxRows = (request.maxRows == null || request.maxRows < 1)
? 20
: Math.min(request.maxRows, 50);
Date since = request.createdAfter == null
? Date.newInstance(1900, 1, 1)
: request.createdAfter;
Datetime sinceTime = Datetime.newInstance(since, Time.newInstance(0, 0, 0, 0));
return [
SELECT Id, Name, Email
FROM Contact
WHERE Name LIKE :key AND CreatedDate >= :sinceTime
WITH USER_MODE
ORDER BY Name
LIMIT :maxRows
];
}
}The component sends the request object under the key request:
import { LightningElement } from 'lwc';
import search from '@salesforce/apex/ContactSearchController.search';
export default class AdvancedContactSearch extends LightningElement {
term = '';
maxRows = '';
createdAfter = '';
contacts = [];
errorMessage;
handleChange(event) {
this[event.target.name] = event.target.value;
}
async handleSearch() {
this.errorMessage = undefined;
try {
this.contacts = await search({
request: {
term: this.term,
maxRows: this.maxRows === '' ? null : Number(this.maxRows),
createdAfter: this.createdAfter || null
}
});
} catch (error) {
this.contacts = [];
this.errorMessage = error?.body?.message || error?.message || 'Unknown error';
}
}
}Notice that the Apex code treats every field as optional. Never trust that the client sent a sensible value. The server clamps maxRows to 50, and the component cannot override that.
Details that cause bugs
Reactive and read-only objects
Objects that come from @wire results or from other components are often read-only proxies. You can pass them as parameters, because serialization reads them without changing them. You cannot modify them first. If you need to change a field before sending it, copy it:
const payload = { ...this.record, Email: this.email };
await saveContact({ contact: payload });Values that do not serialize
Functions, DOM elements, and Symbol values cannot be converted to JSON. Dates as Date objects are converted to ISO strings, which works for Datetime but can shift the calendar day for a Date parameter because of time zones. For a Date-only value, send the 'YYYY-MM-DD' string and do not call toISOString() on a local date.
Lists of Ids
An Id list is an array of strings. A single invalid element fails the whole call, so filter out empty values before sending:
const ids = this.selectedRows.map((row) => row.Id).filter(Boolean);
await archiveContacts({ contactIds: ids });Parameters and caching
With cacheable=true, the client caches responses by method and parameter values. Calling search again with an identical request object can return the cached result. The next chapters cover refreshing that data. For now, remember that parameters are part of the cache key, so the same input does not guarantee a fresh read.
Size limits
The request payload counts toward the platform's limits, so do not send large records or whole lists when Ids are enough. Send the Ids and query for fields on the server.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Apex parameter is `null` | Key name differs from the Apex parameter | Match the name exactly |
| Apex parameter is `null` only sometimes | Value was `undefined` | Use `null` or a default |
| Error about an invalid Id | Empty string or malformed value sent to an `Id` parameter | Send `null` or validate first |
| Class parameter has empty fields | Properties lack `@AuraEnabled` | Annotate each property |
| Date is a day off | `toISOString()` on a local date | Send `'YYYY-MM-DD'` |
Exercise
A component calls updateEmail(this.recordId, this.email) and nothing happens on the server. What is wrong, and what is the corrected call?
Show answer
Imported Apex methods take one object whose keys are the Apex parameter names, not positional arguments. The corrected call is await updateEmail({ contactId: this.recordId, email: this.email });.
Exercise
An Apex method has the signature getOrders(Id accountId, Integer maxRows). A component sends { accountId: this.recordId, maxRow: 10 }. The method runs but ignores the limit. Why, and how do you fix it?
Show answer
The key maxRow does not match the Apex parameter maxRows, so maxRows is null on the server. Rename the key to maxRows. Also give the Apex code a default for a null value, so a missing parameter does not change the behavior unexpectedly.
Exercise
A lightning-input type="number" holds the value 25. Why should you call Number() on it before passing it to an Integer parameter, and what should you send when the field is empty?
Show answer
event.target.value is always a string. Converting it makes the type explicit and avoids relying on server-side coercion. When the field is empty, send null (not 0 or '') so the Apex code can distinguish "no value" and apply its default.