Sub topic 14
Running a flow inside an LWC with lightning-flow
This chapter assumes you know how to write a Lightning web component and handle its events. It also assumes you can build a screen flow with input and output variables. Earlier chapters put components inside flows. Here the direction reverses: a component hosts a flow.
When to embed a flow in a component
A flow screen component runs inside Flow Builder's runtime. The lightning-flow base component works the other way around. You place it in your own component's template, and it renders a screen flow in that spot. Your component supplies the starting values and listens for progress and results.
Embedding makes sense in these cases:
- A record page, utility bar, or modal already has a custom component, and you want a guided process inside it.
- The surrounding component needs the flow's results, for example to refresh a list or show a confirmation.
- Admins own the process logic in the flow, while developers own the page around it.
Embedding is a poor fit when a plain flow on a Lightning page would do. Use the standard Flow component on the page first. Reach for lightning-flow only when you need code to react to the flow.
The lightning-flow component
You start a flow by naming it in the template. The main attributes are:
| Attribute | Purpose |
|---|---|
| `flow-api-name` | API name of the flow to run. The flow must be active and be a screen flow. |
| `flow-input-variables` | Array of objects with `name`, `type`, and `value`. Sets the flow's input variables. |
| `flow-guid` | The interview ID of a paused interview to resume. |
| `onstatuschange` | Handler that runs whenever the flow's status changes. |
Each entry in flow-input-variables has this shape:
{ name: 'accountId', type: 'String', value: '001000000000001AAA' }The name must match the flow variable's API name exactly. The flow variable must also have Available for input selected, or the value is ignored. The type is a flow data type such as String, Number, Boolean, Currency, Date, DateTime, or SObject.
What happens at runtime
The component starts the flow when it renders. Each time the flow moves, lightning-flow fires statuschange. Your handler receives the new status and, when the flow ends, its output values.
The event.detail object carries these properties:
| Property | Meaning |
|---|---|
| `status` | One of `STARTED`, `PAUSED`, `FINISHED`, `FINISHED_SCREEN`, or `ERROR`. |
| `outputVariables` | Array of `{ name, type, value }` for variables marked **Available for output**. |
| `interviewGuid` | ID of the interview. Save it if the flow can pause. |
| `flowTitle` | The title of the current flow. |
| `helpText` | Help text of the current screen. |
| `activeStages` | Names of the active stages. |
| `currentStage` | Name of the stage the flow is in. |
The statuses mean the following:
STARTED: the interview began or moved to a new screen.PAUSED: the user paused, and the interview was saved.FINISHED: the flow ended and showed no final screen.FINISHED_SCREEN: the flow ended on a screen, and the user has seen it.ERROR: the flow failed.
A flow can end on a screen or end silently. Your handler should treat FINISHED and FINISHED_SCREEN as the two ways to succeed.
A worked example: create a case from an account page
The flow is a screen flow named Create_Case_For_Account. It has these variables:
accountId: Text, Available for input.newCaseId: Text, Available for output.
The flow shows screens that collect a subject and a priority, creates a Case, and stores its ID in newCaseId.
Start with the template. It shows the flow until it finishes, then switches to a confirmation.
<template>
<lightning-card title="Open a case">
<div class="slds-var-p-around_medium">
<template lwc:if={isFinished}>
<p>Case {newCaseId} was created.</p>
<lightning-button
label="Start another"
onclick={handleRestart}>
</lightning-button>
</template>
<template lwc:elseif={errorMessage}>
<p class="slds-text-color_error">{errorMessage}</p>
</template>
<template lwc:else>
<lightning-flow
flow-api-name="Create_Case_For_Account"
flow-input-variables={inputVariables}
onstatuschange={handleStatusChange}>
</lightning-flow>
</template>
</div>
</lightning-card>
</template>Now the JavaScript. The inputVariables getter builds the array from recordId, and the handler reads the output.
import { LightningElement, api } from 'lwc';
export default class CaseFlowHost extends LightningElement {
@api recordId;
isFinished = false;
newCaseId;
errorMessage;
get inputVariables() {
return [
{ name: 'accountId', type: 'String', value: this.recordId }
];
}
handleStatusChange(event) {
const { status, outputVariables } = event.detail;
if (status === 'FINISHED' || status === 'FINISHED_SCREEN') {
const caseVar = (outputVariables || []).find(
(v) => v.name === 'newCaseId'
);
this.newCaseId = caseVar ? caseVar.value : undefined;
this.isFinished = true;
this.dispatchEvent(
new CustomEvent('caseCreated', {
detail: { caseId: this.newCaseId }
})
);
} else if (status === 'ERROR') {
this.errorMessage =
'The flow could not be completed. Contact your administrator.';
}
}
handleRestart() {
this.isFinished = false;
this.newCaseId = undefined;
this.errorMessage = undefined;
}
}The meta.xml file exposes the component on Account record pages:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>60.0</apiVersion>
<isExposed>true</isExposed>
<masterLabel>Case Flow Host</masterLabel>
<targets>
<target>lightning__RecordPage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
</objects>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>Three details in this example matter.
First, the template removes lightning-flow from the DOM once the flow finishes. Because the lwc:else branch re-renders when handleRestart resets the state, the flow starts again from its first screen. A finished interview does not restart itself.
Second, outputVariables can be missing or empty. The code guards for that instead of assuming the variable exists.
Third, the host sends its own caseCreated event upward. Parents then react to the result without knowing a flow is involved.
Passing records and collections
Input variables of type SObject take a record object as their value. The flow variable must be a record variable of the matching object type.
get inputVariables() {
return [
{
name: 'selectedContact',
type: 'SObject',
value: { Id: this.contactId, LastName: this.lastName }
}
];
}For a collection, pass an array as the value and use the same type. Only include fields the flow needs, and make sure the field names match the object's API names.
Pausing and resuming
When the flow allows pausing, the user can pause and the status becomes PAUSED. The event's interviewGuid identifies the saved interview. Store it, for example in a custom field or a component property, and pass it later:
<lightning-flow
flow-guid={savedInterviewId}
onstatuschange={handleStatusChange}>
</lightning-flow>When you set flow-guid, you do not set flow-api-name. The saved interview already knows which flow it belongs to. The resumed interview also keeps the input values from the first run, so changes to flow-input-variables do not apply.
Gotchas
- Changing inputs does not restart the flow. Updating
flow-input-variablesafter the flow has started has no effect on the running interview. To re-run with new inputs, remove the component from the DOM and add it again, as the example does. - Variable access flags are required. A variable not marked for input or output is invisible to the host. The failure is silent: a wrong name or missing flag produces no error, only a missing value.
- Run context matters. The flow runs with the permissions of the current user. A user without access to the objects the flow touches sees the flow fail with
ERROR. - Only active flows run. If you deactivate the flow or point
flow-api-nameat a misspelled name, the status isERROR. - Output arrives only at the end. You cannot read variable values from earlier screens through
outputVariables. If the host needs intermediate data, have the flow finish, or design the flow into smaller flows.
Choosing between embedding and other options
| Need | Use |
|---|---|
| Show a flow on a page with no custom code | The standard Flow component in App Builder |
| React in code to a flow's result | `lightning-flow` in your own component |
| Put custom UI on a flow screen | An LWC with the `lightning__FlowScreen` target |
| Reuse a flow's logic from Apex | Invoke the flow from Apex, which skips screens |
You can combine the first two directions. A flow can contain your screen component, and a host component can run that flow.
Exercise
A host component starts a flow with flow-input-variables containing { name: 'orderId', type: 'String', value: 'A1' }. The flow runs, but its orderId variable is empty. The names match. What is the most likely cause, and how do you fix it? Also, a later change to the array to 'B2' does not update the running flow. Why?
Show answer
The flow variable orderId is probably not marked Available for input, so the runtime ignores the value. Select that option in the flow's variable settings and activate the new version. The later change has no effect because a running interview reads its input variables only when it starts. To apply new values, remove lightning-flow from the DOM and render it again, which starts a new interview.
Exercise
Write the condition in a statuschange handler that treats both ways of ending a flow as success and reads an output variable named result without throwing if no output variables exist.
Show answer
if (status === 'FINISHED' || status === 'FINISHED_SCREEN') { const v = (outputVariables || []).find((o) => o.name === 'result'); const result = v ? v.value : undefined; }