Embed Screen Flows in Lightning Web Component

Advertisements

Last Updated on July 19, 2023 by Rakesh Gupta

Big Idea or Enduring Question:

  • How do you embed a screen flow within a lightning web component?

Objectives:

After reading this blog, you’ll be able to:

  • Embed the screen flow inside a lightning web component
  • Apply conditional rendering in lightning web component
  • Use uiRecordApi to fetch the record’s field value without using the Apex class
  • and much more

In the past, I have written a few articles on Lightning Web Component. Why not check them out while you are at it?!

  1. Pass Data From Lightning Web Component to Screen Flow
  2. Using Lightning Web Component to Show an Alert Banner

Business Use case

Janel Parrish is working as a Junior Developer at Gurukul on Cloud (GoC). She has been tasked with a business requirement to develop an LWC component with the following functionalities:

  1. It should display a screen flow named ‘parterFlow’ when the account type is ‘Technology Partner’.
  2. It should present a screen flow named ‘customerFlow’ when the account type is ‘Customer – Direct’.
  3. The LWC component should be designed with the capability to be incorporated into the account lightning record page.

Automation Champion Approach (I-do):

We will utilize the lightning-flow component to embed a screen flow in the lightning web component. To create a flow in the lightning web component, set the lightning-flow component’s flowApiName attribute to the flow name you want to use. The component includes navigation buttons (Back, Next, Pause, and Finish) for users to navigate within the flow.

We will also use a uiRecordApi wire adapter that allows us to interact with Salesforce records from the lightning web component components without writing Apex code. This API allows you to perform operations like retrieving a record’s data or layout details, creating, deleting, or updating a record, and so on.  Here are some of the key methods provided by uiRecordApi:

  1. getRecord – This method allows you to fetch record data.
  2. getRecordCreateDefaults – This method provides the default values that Salesforce uses when creating a new record.
  3. getRecordUiIt fetches the layout details for a record, like which fields are displayed, how they are displayed, and so on.
  4. createRecord – This method enables you to create a new record.
  5. deleteRecord – It allows you to delete a record.
  6. updateRecord – It lets you update an existing record.

In the XML configuration file, we will use lightning__RecordPage as the target to enable the lighting web component to be used on a record page in Lightning App Builder.

Guided Practice (We-do):

There are 3 steps to solve Janel’s business requirement using Lightning Web Component and Screen Flow. We must:

  1. Create a ScreenFlow (customerFlow) to handle customer request
    1. Define flow properties for screen flow
    2. Add a Text variable to store Account Name
    3. Add a Screen to display the Account Name from a text variable
  2. Create a ScreenFlow (partnerFlow) to handle customer request 
    1. Define flow properties for screen flow
    2. Add a Text variable to store Account Name
    3. Add a Screen to display the Account Name from a text variable
  3. Create a lightning web component to display the different Screen Flows based on the account type

Step 1.1: Define Flow Properties (customerFlow)

  1. Click Setup.
  2. In the Quick Find box, type Flows.
  3. Select Flows, then click on the New Flow.
  4. Select the Screen Flow option and click on Create and Configure the flow.
  5. It will open the flow designer for you.

Step 1.2: Add a Text Variable to Store Account Name

  1. Under Toolbox, select Managerthen click New Resource to store the account name. 
  2. Input the following information
    1. Resource Type: Variable
    2. API Name: accountName
    3. Data Type: Text
    4. Default Value{!$GlobalConstant.EmptyString}
    5. Check Available for Input
    6. Check Available for Output
  3. Click Done.

Step 1.3: Add a Screen to display the Account Name from Text Variable

  1. On Flow Designer, click on the +icon and select the Screen element.
  2. Input the following information:
    1. Enter Label the API Name will auto-populate.
  3. Click Done.

In the end, Janel’s Flow will look like the following screenshot:

Once everything looks good, perform the steps below:

  1. Click Save.
  2. Enter Flow Label the API Name will auto-populate.
  3. Click Show Advanced.
  4. API Version for Running the Flow: 58
  5. Interview LabelcustomerFlow {!$Flow.CurrentDateTime}
  6. Click Save.

Step 2.1: Define Flow Properties (partnerFlow)

  1. Click Setup.
  2. In the Quick Find box, type Flows.
  3. Select Flows, then click on the New Flow.
  4. Select the Screen Flow option and click on Create and Configure the flow.
  5. It will open the flow designer for you.

Step 2.2: Add a Text Variable to Store Account Name

  1. Under Toolbox, select Managerthen click New Resource to store the account name. 
  2. Input the following information
    1. Resource Type: Variable
    2. API Name: accountName
    3. Data Type: Text
    4. Default Value{!$GlobalConstant.EmptyString}
    5. Check Available for Input
    6. Check Available for Output
  3. Click Done.

Step 2.3: Add a Screen to display the Account Name from Text Variable

  1. On Flow Designer, click on the +icon and select the Screen element.
  2. Input the following information:
    1. Enter Label the API Name will auto-populate.
  3. Click Done.

In the end, Janel’s Flow will look like the following screenshot:

Once everything looks good, perform the steps below:

  1. Click Save.
  2. Enter Flow Label the API Name will auto-populate.
  3. Click Show Advanced.
  4. API Version for Running the Flow: 58
  5. Interview Label: partnerFlow {!$Flow.CurrentDateTime}
  6. Click Save.

Step 3: Create a Lightning Web Component to Display the Different Screen Flows Based on The Account Type

Below lightning web component template displays a Lightning card titled Initiate Order. Depending on whether the isPartner or isCustomer property is true, it will launch and display the corresponding Lightning Flow (“rakeshistomMVP__partnerFlow” or “rakeshistomMVP__customerFlow”).

embedFlowToLWC.html

We will utilize the lightning-flow component to embed a screen flow in the lightning web component. Let’s break down the code:

  • In LWC, every component’s HTML file must be wrapped with a <template> tag.
  • <template if:true={isPartner}> and <template if:true={isCustomer}>: These are conditional templates that display content based on the truthiness of the isPartner and isCustomer properties, respectively. The content inside these templates will only render if the corresponding condition is true.

<template>
    <div class="slds-m-around_medium">
        <lightning-card title="Initiate Order" icon-name="standard:orders">
            <div class="slds-m-around_medium">
                <template if:true={isPartner}>
                    <lightning-flow onstatuschange={handleStatusChange} flow-api-name="rakeshistomMVP__partnerFlow" flow-input-variables={inputVariables}></lightning-flow>
                </template>
                <template if:true={isCustomer}>
                    <lightning-flow onstatuschange={handleStatusChange} flow-api-name="rakeshistomMVP__customerFlow" flow-input-variables={inputVariables}></lightning-flow>
                </template>
            </div>
        </lightning-card>
    </div>
</template>

embedFlowToLWC.js

This sample JavaScript code uses the @api decorator to create public properties. For example, recordId is a public reactive property that holds the ID of the record page. Whereas the @wire decorator reads Salesforce data. getRecord is a lightning/uiRecordApi module function that retrieves a record. accountType and accountName are imported from the Salesforce schema.

  • The import statements are used to import the required modules and dependencies. LightningElement is the basic building block for creating Lightning Web Components.
  • account({ error, data }) is a function that handles the response from the getRecord call. If there’s an error, it assigns the error to this.error. If data is returned, it sets this.accountName to the account’s name and sets isPartner or isCustomer to true depending on the account’s type.
  • get inputVariables() is a getter method that returns an array of objects, which represents input variables for a flow. In this case, it returns the account name.

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import accountType from '@salesforce/schema/Account.Type';
import accountName from '@salesforce/schema/Account.Name';

export default class FlowLauncher extends LightningElement {
    @api recordId;
    accountName;
    isPartner = false;
    isCustomer = false;

    @wire(getRecord, { recordId: '$recordId', fields: [accountName, accountType] })
    account({ error, data }) {
        if (error) {
            this.error = error;
        } else if (data) {
            this.accountName = data.fields.Name.value;
            if(data.fields.Type.value === 'Technology Partner') { 
                this.isPartner = true;
                this.isCustomer = false;
            }
            else if(data.fields.Type.value === 'Customer - Direct') {
                this.isCustomer = true;
                this.isPartner = false;
            }
        }
    }

    get inputVariables() {
        return [
            {
                name: 'accountName',
                type: 'String',
                value: this.accountName
            }
        ];
    }

    handleStatusChange(event) {
        if(event.detail.status === 'FINISHED') {
            //Action after a flow has finished
        }
    }
}

embedFlowToLWC.js-meta.xml

The isExposed element is set to true, which makes the component available for use in tools like the Lightning App Builder or Flow Builder.

The targets element is used to specify where your component can be used. In this case, the lightning__RecordPage tag means that this component is intended to be used on a record page in Lightning App Builder.


<?xml version=”1.0″ encoding=”UTF-8″?>
<LightningComponentBundle xmlns=”http://soap.sforce.com/2006/04/metadata”>
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>

Proof of Concept

Formative Assessment:

I want to hear from you!

What is one thing you learned from this post? How do you envision applying this new knowledge in the real world? Feel free to share in the comments below.

Have feedback, suggestions for posts, or need more information about Salesforce online training offered by me? Say hello, and leave a message!

Preferred Timing(required)

2 thoughts on “Embed Screen Flows in Lightning Web Component

    1. Rakesh Gupta – Mumbai – 9x Salesforce MVP | Senior Solution Architect | 8x Author | 5x Dreamforce Speaker | Salesforce Coach | Co-host of AutomationHour.com and AppXchangeHour.Com

      Multiple approaches exist for addressing the given business use case. In this particular guide focused on LWC, I used both LWC and Flow to solve it.

      An alternative option is to utilize two flows and then use the component visibility or the method you mentioned above. Thank you 😊

Leave a ReplyCancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Automation Champion

Subscribe now to keep reading and get access to the full archive.

Continue reading

Exit mobile version
%%footer%%