Sub topic 4
Returning structured data with wrapper classes
This chapter assumes you can write Apex classes and SOQL queries and that you have built a Lightning web component that calls a method with @wire. It also assumes you know what @AuraEnabled and cacheable=true do on a method. The chapter covers how to return more than one SObject from a method, and the rules that decide what reaches the browser.
Why return a wrapper class
An @AuraEnabled method can return an SObject or a list of SObjects, as getContacts does in the earlier chapters. That works when the component needs exactly the fields of one object. Often it needs something else:
- Values from several objects in one round trip, such as an account name and its contacts.
- Computed values, such as a count, a flag or a display label.
- A smaller payload, so the component never receives fields it does not use.
- A stable contract. The shape the component depends on does not change when the object model does.
A wrapper class is an Apex class that exists only to carry data. You declare it, mark the members you want to send with @AuraEnabled, fill it in the method and return it.
The basic pattern
This is the example from the plan, reduced to its essentials.
public with sharing class AccountSummaryController {
public class Summary {
@AuraEnabled public String name;
@AuraEnabled public Integer contactCount;
}
@AuraEnabled(cacheable=true)
public static Summary getSummary(Id accountId) {
Account acc = [
SELECT Name, (SELECT Id FROM Contacts)
FROM Account
WHERE Id = :accountId
WITH USER_MODE
];
Summary result = new Summary();
result.name = acc.Name;
result.contactCount = acc.Contacts.size();
return result;
}
}The component receives a plain JavaScript object with the properties name and contactCount. The Apex class name and the Summary type do not appear on the client.
import { LightningElement, api, wire } from 'lwc';
import getSummary from '@salesforce/apex/AccountSummaryController.getSummary';
export default class AccountSummary extends LightningElement {
@api recordId;
@wire(getSummary, { accountId: '$recordId' })
summary;
}In the template, read summary.data.name and summary.data.contactCount.
What gets serialized
Apex serializes the returned object to JSON, and only some members are included.
| Member | Sent to the component? |
|---|---|
| Instance field with `@AuraEnabled` | Yes |
| Instance property (`{ get; set; }`) with `@AuraEnabled` | Yes |
| Public field without `@AuraEnabled` | No. The property is missing from the JavaScript object. |
| Private or protected member | No, even with the annotation, because it must be accessible |
| Static or constant member | No |
| Methods | No |
The wrapper class itself does not need an annotation. It does need to be public or global, and an inner class is fine, as above.
Allowed member types
A wrapper member can be any type that an @AuraEnabled method can return:
- Primitives such as
String,Integer,Decimal,Boolean,Id,DateandDatetime. - SObjects, either generic or a specific type such as
Contact. - Lists, sets and maps of those types.
- Other Apex classes whose own members are annotated. This allows nesting.
Dates arrive in JavaScript as strings, not as Date objects. A Date becomes a value like "2026-11-30" and a Datetime becomes an ISO 8601 timestamp. Convert them in the component with new Date(value) if you need date arithmetic. For display, prefer lightning-formatted-date-time.
A fuller example with nesting and computed values
The next controller returns an overview with a nested list. Each contact is shaped for display, and the overview carries a derived count. A constructor on the inner class keeps the mapping code in one place.
public with sharing class AccountOverviewController {
public class ContactInfo {
@AuraEnabled public Id contactId;
@AuraEnabled public String displayName;
@AuraEnabled public Boolean hasEmail;
public ContactInfo(Contact c) {
this.contactId = c.Id;
this.displayName = c.Name;
this.hasEmail = String.isNotBlank(c.Email);
}
}
public class Overview {
@AuraEnabled public String name;
@AuraEnabled public Integer emailCount = 0;
@AuraEnabled public List<ContactInfo> contacts = new List<ContactInfo>();
}
@AuraEnabled(cacheable=true)
public static Overview getOverview(Id accountId) {
Account acc = [
SELECT Name,
(SELECT Id, Name, Email FROM Contacts ORDER BY Name LIMIT 50)
FROM Account
WHERE Id = :accountId
WITH USER_MODE
];
Overview result = new Overview();
result.name = acc.Name;
for (Contact c : acc.Contacts) {
ContactInfo info = new ContactInfo(c);
result.contacts.add(info);
if (info.hasEmail) {
result.emailCount++;
}
}
return result;
}
}Three details are worth noting:
- Field initializers (
= 0and= new List<ContactInfo>()) guarantee the component never sees anulllist. The template can iteratecontactswithout a null check. ContactInfodefines a constructor that takes a parameter, so Apex does not generate a no-argument constructor for it. That is fine for a class used only as output. A class you also accept as an input parameter may need an explicit no-argument constructor.- Only the fields the component needs leave the server. The contact's
Emailvalue is reduced to a boolean.
The component reads the nested structure with ordinary property access.
import { LightningElement, api, wire } from 'lwc';
import getOverview from '@salesforce/apex/AccountOverviewController.getOverview';
export default class AccountOverview extends LightningElement {
@api recordId;
@wire(getOverview, { accountId: '$recordId' })
overview;
}<template>
<template lwc:if={overview.data}>
<h2>{overview.data.name}</h2>
<p>{overview.data.emailCount} contacts have an email address.</p>
<ul>
<template for:each={overview.data.contacts} for:item="c">
<li key={c.contactId}>{c.displayName}</li>
</template>
</ul>
</template>
</template>Each item in a for:each loop needs a unique key. The wrapper's contactId supplies one.
The data path
Wrappers compared with returning SObjects
| Concern | Return SObjects | Return a wrapper |
|---|---|---|
| Code to write | Least | More: class plus mapping code |
| Data from several objects | Needs relationship fields or several calls | One call, any shape |
| Computed values | Not possible | Easy |
| Payload size | Whole queried records | Only the fields you choose |
| Coupling to the schema | Component uses field API names | Component uses names you control |
Choose SObjects when the component displays one object's fields as they are. Choose a wrapper when the data crosses objects, has computed parts, or should not expose the underlying fields.
Wrapper classes and security
A wrapper does not change the security model. The query still runs with with sharing and WITH USER_MODE, so the user's record access and field permissions apply when you read the data. Two points follow from this:
- If you build the wrapper from records queried in system mode, you can send data the user should not see. Keep queries in user mode, as in the examples.
- Copying only the fields you need into the wrapper is a good habit, but the wrapper is not a security boundary. Anything you place in an
@AuraEnabledmember is visible to the user in the browser's network tools.
Wrappers as input parameters
A method can also accept a wrapper class as a parameter. The component passes a JavaScript object, and the framework copies its properties into the @AuraEnabled members of the Apex class by name.
public with sharing class ContactRequestController {
public class ContactRequest {
@AuraEnabled public String lastName;
@AuraEnabled public Id accountId;
}
@AuraEnabled
public static Id createContact(ContactRequest request) {
Contact c = new Contact(LastName = request.lastName, AccountId = request.accountId);
insert as user c;
return c.Id;
}
}From the component, call it with createContact({ request: { lastName: 'Smith', accountId: this.recordId } }). The outer key is the Apex parameter name and the inner keys are the wrapper's member names. Misspelled member names are ignored, and the Apex member stays null. This is a common source of "the value never arrives" bugs.
Common errors
- Property is
undefinedin the component. The member lacks@AuraEnabled, or the JavaScript name does not match the Apex name. Names are case sensitive on the client. SObject row was retrieved via SOQL without querying the requested field. The mapping code reads a field the query did not select. Add it to theSELECTlist.- Attempt to modify wired data fails. Data from
@wireis read-only. Copy it first, for example{ ...this.overview.data }, or map the list into new objects, before changing anything. - The result looks stale after an update. The method is
cacheable=true, so you needrefreshApex, covered in a later chapter.
Testing a wrapper method
A wrapper-returning method is tested like any other. Create data, call the method and assert on the members of the result.
@IsTest
private class AccountOverviewControllerTest {
@IsTest
static void buildsOverview() {
Account a = new Account(Name = 'Test Account');
insert a;
insert new List<Contact>{
new Contact(LastName = 'Adams', Email = '[email protected]', AccountId = a.Id),
new Contact(LastName = 'Brown', AccountId = a.Id)
};
Test.startTest();
AccountOverviewController.Overview result =
AccountOverviewController.getOverview(a.Id);
Test.stopTest();
Assert.areEqual('Test Account', result.name, 'Name should be copied');
Assert.areEqual(2, result.contacts.size(), 'Both contacts should be listed');
Assert.areEqual(1, result.emailCount, 'Only one contact has an email');
}
}The test sees the wrapper as an Apex object, so it does not prove that every member is annotated. Review the annotations when you write the class, and check the component output in a sandbox.
Exercise
A component calls a cacheable method that returns a wrapper with the members @AuraEnabled public String title; and public Integer total;. The component shows the title but total is blank. The method does not throw an error. What is wrong, and how do you fix it?
Show answer
total has no @AuraEnabled annotation, so the framework leaves it out when it serializes the wrapper. The component receives an object with only title, and reading total gives undefined. Add @AuraEnabled to the declaration (@AuraEnabled public Integer total;), save, and reload the component. Because the method is cacheable, a hard refresh may be needed to clear a cached result.
Exercise
Why might the Apex mapping code throw an SObjectException when it copies c.Phone into a wrapper member, even though Phone is a valid field on Contact?
Show answer
The SOQL query did not include Phone in its SELECT list. Apex only populates fields that the query selected, and reading any other field throws an SObjectException. Add Phone to the query, or stop reading it in the mapping code.