Sub topic 12
Passing Apex-defined types
This chapter assumes you can build a screen flow component with the lightning__FlowScreen target. It also assumes you know how @api properties, FlowAttributeChangeEvent, and validate() work, and that you can write a basic Apex class. Earlier chapters covered the first three. Here you will pass structured data between the flow and the component without flattening it into many separate String and Number properties.
Why use an Apex-defined type
A flow can pass primitives (String, Integer, Boolean, Date) and sObjects to a component. Real screens often need something in between: a shopping cart line, a quote summary, or a search result that mixes fields from several objects. An sObject does not fit these, and passing ten loose properties is clumsy.
An Apex-defined type is a plain Apex class that you mark up so Flow Builder treats it as a data type. The flow can then:
- create variables of that class, including collections of it;
- fill them from an Apex action, or from the output of your component;
- pass them into your component as a single property.
This is also the usual way to hand a component the result of an invocable Apex action without a round trip through a custom object.
Requirements for the Apex class
Flow Builder only recognizes a class that meets these rules:
- The class is
publicorglobal. - Each field you want to expose is a member variable annotated with
@AuraEnabled. Fields without the annotation are invisible to the flow and to the component. - Field types are ones Flow supports: Boolean, Date, Datetime, Decimal, Double, Integer, Long, String, Id, sObject, another Apex-defined class, or a List of these.
public with sharing class LineItem {
@AuraEnabled public String sku;
@AuraEnabled public String description;
@AuraEnabled public Integer quantity;
@AuraEnabled public Decimal unitPrice;
}Deploy the class before the component bundle. The meta.xml file references the class by name, and the deployment fails if the class does not exist yet.
Declaring the type in meta.xml
In meta.xml you reference the class with the apex:// prefix, followed by the class name. A list uses [] after the name. This differs from generic sObject properties, which use a propertyType with {T} placeholders.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Line Item Picker</masterLabel>
<targets>
<target>lightning__FlowScreen</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__FlowScreen">
<property name="items" type="apex://LineItem[]" role="inputOnly" label="Available items" description="Items the user can choose from"/>
<property name="selectedItem" type="apex://LineItem" label="Selected item" description="The chosen item, with the quantity the user entered"/>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>Points to check:
itemsis a collection and isinputOnly. The flow supplies it and never reads it back.selectedItemhas no role, so it works as both input and output. The flow can preselect an item, and the component can change it.- If the class is in a managed package, include the namespace:
apex://ns__LineItem. - The name must match the class exactly, including capitalization of the class name.
In Flow Builder, a variable can only be mapped to this property if its data type is the Apex-defined type LineItem and its collection setting matches. A single-record variable will not appear in the list for items.
How the data moves
The component never receives an instance of the Apex class. It receives a plain JavaScript object (or array of objects) whose keys are the @AuraEnabled field names. There is no JavaScript class to construct, and no method calls are possible.
Writing the component
The component below shows the items as buttons. After a selection it shows a quantity field. Every change sends a new object back to the flow.
<template>
<div class="slds-var-m-bottom_small">
<template for:each={rows} for:item="row">
<lightning-button
key={row.sku}
label={row.description}
data-sku={row.sku}
variant={row.variant}
onclick={handleSelect}>
</lightning-button>
</template>
</div>
<template lwc:if={selectedItem}>
<lightning-input
type="number"
label="Quantity"
value={selectedItem.quantity}
min="1"
step="1"
onchange={handleQuantity}>
</lightning-input>
</template>
</template>import { LightningElement, api } from 'lwc';
import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
export default class LineItemPicker extends LightningElement {
@api items = [];
@api selectedItem;
get rows() {
return (this.items || []).map((item) => ({
...item,
variant: this.selectedItem && this.selectedItem.sku === item.sku
? 'brand'
: 'neutral'
}));
}
handleSelect(event) {
const sku = event.currentTarget.dataset.sku;
const match = (this.items || []).find((item) => item.sku === sku);
if (!match) {
return;
}
this.updateSelection({ ...match, quantity: match.quantity || 1 });
}
handleQuantity(event) {
const parsed = parseInt(event.detail.value, 10);
this.updateSelection({
...this.selectedItem,
quantity: Number.isNaN(parsed) ? undefined : parsed
});
}
updateSelection(next) {
this.selectedItem = next;
this.dispatchEvent(new FlowAttributeChangeEvent('selectedItem', next));
}
@api validate() {
const item = this.selectedItem;
if (item && Number.isInteger(item.quantity) && item.quantity > 0) {
return { isValid: true };
}
return {
isValid: false,
errorMessage: 'Choose an item and enter a quantity of at least 1.'
};
}
}Copy objects, do not edit them
The objects in items come from the flow and are read-only. Writing this.selectedItem.quantity = 3 throws an error in strict mode, or does nothing. Always build a new object with the spread operator, as updateSelection does. A spread copy is shallow. If your Apex class contains a nested Apex-defined type or a list, those inner values are still read-only, so copy them too (structuredClone works for plain data) before changing them.
Send the whole object
FlowAttributeChangeEvent replaces the flow variable's value. It does not merge fields. If you send { quantity: 3 } alone, sku, description, and unitPrice are lost. Always send the complete object.
Using the output in the flow
After the screen, the flow variable mapped to selectedItem holds the object. You can:
- read its fields with dot notation, for example
{!selectedLine.quantity}; - compute totals in a formula that uses
{!selectedLine.unitPrice}and{!selectedLine.quantity}; - pass the variable to an invocable Apex action that takes a
LineIteminput.
To get a collection back from the component, declare a LineItem[] property and send an array. Send a new array each time. The flow compares by reference, so pushing onto the existing array can leave the flow unaware of the change.
Common errors
| Symptom | Likely cause | Column | Column |
|---|---|---|---|
| The property does not appear in Flow Builder | The class is missing, is not public or global, or is misspelled in `type="apex://..."`. Redeploy the class first. | ||
| The variable list for the property is empty | The flow variable is not of the same Apex-defined type, or its collection setting differs. | ||
| A field is always `undefined` in the component | The Apex field lacks `@AuraEnabled`, or the flow never populated it. | ||
| `items` is `undefined` on first render | The flow passed an empty collection or nothing at all. Guard with `(this.items \ | \ | [])`. |
| Other fields vanish after an edit | The component sent a partial object in `FlowAttributeChangeEvent`. | ||
| "Cannot assign to read only property" | The component modified an input object directly instead of copying it. |
Design notes
- Keep the class small. Every field you add becomes part of the contract between the flow and the component, and renaming a field later breaks flows that use it.
- Changing a class that flows already use can break them. Adding a field is safe. Removing or renaming one is not.
- Use an Apex-defined type when the data has a stable shape that Apex produces or consumes. Use a generic sObject property, from the earlier chapter, when the component should work with any object.
- Date and Datetime fields reach JavaScript as strings. Convert them for display, and send them back in the same format you received.
Exercise
A component declares <property name="cart" type="apex://LineItem[]"/>. When the user removes a line, the code runs this.cart.splice(index, 1) and then dispatches FlowAttributeChangeEvent('cart', this.cart). The flow either throws an error or keeps the old collection. What is wrong, and how do you fix it?
Show answer
The array received from the flow is read-only, and sending the same array reference gives the flow no sign of a change. Build a new array and send that: const next = this.cart.filter((_, i) => i !== index); this.cart = next; this.dispatchEvent(new FlowAttributeChangeEvent('cart', next));
Exercise
You add a String notes field to the LineItem class but never see it in the component's objects. List two things to check.
Show answer
Check that the field is annotated with @AuraEnabled, and that the flow actually populates it (for example, that the Apex action sets it). Also confirm the class change is deployed and the flow variable is using the updated class.