Sub topic 10
Reusable components with generic sObject types
This chapter assumes you can already expose a component with the lightning__FlowScreen target, declare typed properties in meta.xml, and send values back with FlowAttributeChangeEvent. It builds on those pieces to make one component work with any object, such as Account, Contact, or a custom object.
The problem with fixed object types
Suppose you build a component that shows a list of records and lets the user pick one. You could declare its properties with type="@salesforce/schema/Account". That component would only accept Account records. To support Contacts you would have to copy the bundle and change the type.
A generic sObject type removes that duplication. The flow builder chooses the object when they add the component to a screen. The component receives whatever records the flow supplies.
Declaring a generic type
You declare a generic type with a propertyType element inside targetConfig. Properties then refer to it with curly braces.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Record Chooser</masterLabel>
<targets>
<target>lightning__FlowScreen</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__FlowScreen">
<propertyType name="T" extends="SObject" label="Object type" description="The object type of the records"/>
<property name="records" type="{T[]}" label="Records" description="Records to display"/>
<property name="selectedRecord" type="{T}" label="Selected record" role="outputOnly"/>
<property name="displayField" type="String" label="Field to display" default="Name" role="inputOnly"/>
<property name="isRequired" type="Boolean" label="Require a selection" role="inputOnly"/>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>The pieces work like this:
propertyTypedeclares a placeholder namedT. The name is yours to choose.extends="SObject"limits it to sObject types.{T[]}means "a collection of whatever T turns out to be".{T}means "a single record of type T".- Both properties share
T, so Flow Builder forces them to be the same object. A Contact collection cannot be paired with an Account output. displayFieldandisRequiredare ordinary properties. They are markedinputOnlybecause the component never changes them.
The label and description on propertyType appear in Flow Builder as the "Select Object" field when an admin configures the component.
What happens in Flow Builder
When an admin drops the component on a screen, Flow Builder asks for the object type first. Once they choose it, the Records and Selected record properties are bound to that type.
Flow Builder shows only variables that match the chosen type. For records it offers collection variables of that object. For selectedRecord it offers single record variables of that object.
Writing the component
The template shows one button per record. The selected record's button is highlighted.
<template>
<template lwc:if={hasRecords}>
<ul class="slds-m-bottom_small">
<template for:each={rows} for:item="row">
<li key={row.key} class="slds-m-bottom_x-small">
<lightning-button
label={row.label}
variant={row.variant}
data-index={row.index}
onclick={handleSelect}>
</lightning-button>
</li>
</template>
</ul>
</template>
<template lwc:else>
<p>No records to choose from.</p>
</template>
</template>The JavaScript receives the collection, builds the display rows, and reports the choice back.
import { LightningElement, api } from 'lwc';
import { FlowAttributeChangeEvent } from 'lightning/flowSupport';
export default class RecordChooser extends LightningElement {
@api displayField = 'Name';
@api isRequired = false;
@api selectedRecord;
_records = [];
selectedIndex;
@api
get records() {
return this._records;
}
set records(value) {
this._records = Array.isArray(value) ? value : [];
}
get hasRecords() {
return this._records.length > 0;
}
get rows() {
return this._records.map((record, index) => ({
index,
key: record.Id ? record.Id : `row-${index}`,
label: record[this.displayField] ?? '(no value)',
variant: index === this.selectedIndex ? 'brand' : 'neutral'
}));
}
handleSelect(event) {
const index = Number(event.currentTarget.dataset.index);
this.selectedIndex = index;
this.selectedRecord = { ...this._records[index] };
this.dispatchEvent(
new FlowAttributeChangeEvent('selectedRecord', this.selectedRecord)
);
}
@api validate() {
if (this.isRequired && this.selectedIndex === undefined) {
return {
isValid: false,
errorMessage: 'Select a record to continue.'
};
}
return { isValid: true };
}
}Several details in this code matter for generic components.
Guard the collection setter
If the flow variable is empty or was never assigned, records can arrive as undefined or null. The setter normalizes it to an empty array, so map and length never fail. Without the setter, the first render can throw before the flow has supplied any data.
Copy before you output
The collection the flow passes in is read-only. Reading from it is fine, but assigning to a field of a record in it throws an error. The handler therefore copies the record with the spread operator before storing and sending it. If you need to edit field values, edit the copy. Spread makes a shallow copy, which is enough for flat sObject records. Use a deeper copy if your records contain nested objects.
Field names are not known ahead of time
The component cannot hard-code record.Name or record.Email, because T could be any object. The example takes the field API name as a property, displayField, and reads it with bracket notation. If a record lacks that field, the code falls back to a placeholder label. Flow only includes fields that were loaded, so a Get Records element that did not retrieve the display field gives you undefined.
Keys for records without an Id
Records created in the flow with an Assignment element have no Id yet. Using record.Id as the key would give every such row the same undefined key and cause rendering errors. The example falls back to an index-based key.
Limitations to plan for
- No object name arrives with the data. The component gets field values, not the object's API name. If you need the name, for example to call a
lightning-record-form, add a plain String property that the admin fills in. Make the label say that it must match the selected object. - Fields must be loaded. A generic component can only show fields that earlier flow elements retrieved. Document which fields your component expects, and tell admins to use "Choose fields and let Salesforce do the rest" or to list them explicitly.
- One T per property set. Properties that share
Tmust all be the same object. If you need two independent object types, declare two property types, such asTandU. - Only sObject types are generic.
extends="SObject"is the only supported base for this feature, so you cannot write a generic String or Integer property. - Output is a copy. Changes you make inside the component after dispatching the event are not synchronized to the flow. Dispatch again whenever the value changes.
Testing a generic component
Test the same component with at least two objects, because that is the point of making it generic. A practical routine:
- Build a small screen flow with a Get Records element for Accounts, a screen with your component, and a second screen that displays
{!selectedAccount.Name}. - Run the flow and select a record. Confirm that the second screen shows the right name.
- Change the Get Records element to Contacts, update the variable types, and reselect the object type on the component. Run it again.
- Run once with a Get Records element that returns no rows, to test the empty state.
- Set
isRequiredto true and click Next without selecting anything. Confirm that the validation message blocks navigation.
If the component's properties do not appear in Flow Builder, check that you deployed the updated meta.xml and that propertyType appears before the properties that use it.
Summary
A propertyType with extends="SObject" lets one component work for any object. Properties typed {T} and {T[]} are tied together by Flow Builder. In your code you should normalize the incoming collection, treat incoming records as read-only, copy them before output, and read field values by name instead of hard-coding them.
Exercise
Your generic component declares <propertyType name="T" extends="SObject" .../> and a property <property name="records" type="{T[]}" .../>. An admin reports that the component throws an error when the flow's collection variable is empty. What is the likely cause, and how do you fix it?
Show answer
The records value arrives as undefined or null when the variable has no value, and the code calls array methods such as map or reads length on it. Fix it by declaring records with a getter and setter that normalizes the value, for example this._records = Array.isArray(value) ? value : [];, and by rendering an empty-state message when the array is empty.
Exercise
A component receives a record from the flow's records collection and runs record.Name = 'Updated' in its handler. What happens, and what should the code do instead?
Show answer
The assignment fails because records passed in from the flow are read-only. The code should make a copy first, for example const copy = { ...record }; copy.Name = 'Updated';, and then send the copy to the flow with FlowAttributeChangeEvent.
Exercise
You want a component with two independent generic properties: a collection of one object type, and a single record of a different object type. How do you declare this in meta.xml?
Show answer
Declare two property types, for example <propertyType name="T" extends="SObject" .../> and <propertyType name="U" extends="SObject" .../>. Then type one property as {T[]} and the other as {U}. Properties that share a name are forced to the same object, so each independent type needs its own propertyType.