Communication Between Salesforce Flow and LWC

July 28, 2023


 

After completing this unit, you will able to:

1.  What is Lightning Web Component and Flow?

2.  Add Authorize Endpoint Address

3.  Create an Apex Class

4.  Create a Lightning Web Component (LWC)

5.  Create a Flow

6.  Add Flow to the Home Page

 

1.  What is Lightning Web Component and Flow?

Salesforce Lightning Web Components (LWC) is a modern, lightweight framework for building web applications on the Salesforce platform. LWC utilizes the web standards-based programming model, allowing developers to build components using a combination of HTML, CSS, and JavaScript. With LWC, developers can create reusable, modular, and performant components that provide a seamless user experience within the Salesforce ecosystem.

Salesforce Flow is a powerful declarative tool that enables users to build and automate business processes in Salesforce without the need for code. It provides a visual interface where administrators or developers can design flows by arranging and connecting pre-built elements called "flow elements." Flows allow for the automation of complex business processes, data manipulation, and integration with external systems.

In this blog post, we will explore how to call an LWC from a Flow, send a response back from the LWC, and display the response using a Flow screen in Salesforce. This integration allows for seamless communication between the LWC and Flow, providing a flexible and dynamic user interface.

 

2.  Add Authorize Endpoint Address

To add the authorizaction endpoint address in salesforce, please follow the below the steps:

1. From setup, enter the remote site setting and select the Remote Site Settings.

2. Click on the New Remote Site button.

3. Enter Animals_http_Callout as Remote Site Name and https://th-apex-http-callout.herokuapp.com as Remote Site URL.

4. Make sure you Active this remote site setting.

5. Click on the Save button.

 

 

3.  Create an Apex Class

We need to create an apex class named AnimalsCallouts which is called the api and get the response. If we get the response successfully, we send this response back to the Lightning Web Component. So to achieve this, firstly we need the apex class to call the api. Here are the code snippet for the apex class:

public class AnimalsCallouts {
    @AuraEnabled
    public static List<Object> getAnimals(List<String> apiMethodName)
    {
        try
        {
            List<Object> animals = new List<Object>();
            Http http = new Http();
            HttpRequest request = new HttpRequest();
            request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
            request.setMethod(apiMethodName[0]);
            HttpResponse response = http.send(request);
            if(response.getStatusCode() == 200)
            {
                Map<String, Object> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
                animals = (List<Object>) results.get('animals');
            }
            return animals;
        }
        catch(Exception ex)
        {
            throw new AuraHandledException(ex.getMessage());
        }
    }
}

 

4.  Create a Lightning Web Component (LWC)

Now we create lightning web component named launchFlowFromLwc which is call the apex class we created in the above step to get the response.

launchFlowFromLwc.html

<template>
    <template lwc:if={isSpinning}>
        <lightning-spinner alternative-text="Loading..." variant="brand"></lightning-spinner>
    </template>
</template>

 

launchFlowFromLwc.js

import { LightningElement, api } from 'lwc';
import getAnimals from '@salesforce/apex/AnimalsCallouts1.getAnimals';
import { FlowNavigationNextEvent } from 'lightning/flowSupport';

export default class LaunchFlowFromLwc extends LightningElement {
    @api animals = [];
    @api apiMethodName;
    isSpinning  = true;

    connectedCallback(){
        getAnimals({apiMethodName: this.apiMethodName})
        .then((result) => {
            this.animals = result;
            this.error = undefined;
            this.isSpinning  = false;
            const navigateNextEvent = new FlowNavigationNextEvent();
            this.dispatchEvent(navigateNextEvent);
        })
        .catch((error) => {
            this.error = error;
            this.animals = undefined;
            this.isSpinning  = false;
            const navigateNextEvent = new FlowNavigationNextEvent();
            this.dispatchEvent(navigateNextEvent);
        });
    }
}

 

launchFlowFromLwc.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>57.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__FlowScreen</target>
        <target>lightning__HomePage</target>
        <target>lightning__RecordPage</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__FlowScreen">
            <property name="apiMethodName" label="Set Method Name" type="String" role="inputOnly"></property>
            <property name="animals" type="String[]" label="List of Animals" role="outputOnly"/>
        </targetConfig>
</LightningComponentBundle>
 
 

5.  Create a Flow

Now we will create a screen flow to get the result from lwc and show the result on the screen. In this flow we will use the 3 screen elements. This is our flow structure:

 

 

Screen 1:

1.  Navigate to the Flow Builder by going to Setup -> Process Automation -> Flows.

2.  Click on New Flow button and then select Screen Flow.

3.  Add the Screen Element to your flow to take the user input as shown in the figure.

 

 

 

 

 

Screen 2:

Drag and drop the Screen Element to create the second screen. In this screen we will call the Lightning Web Component with the parameter which comes from the first screen and send it to the Lightning Web Component then Lightning Web Component sends the result back to the flow according to the parameter value and we will store the result in the list variable called listOfAnimals.

 

 

 

 

 

Screen 3:

Now it's time to display the Response on the Flow Screen. To do that, we need to create the third screen. In this screen, we will display the result which we stored in the listOfAnimals variable.

 

 

 

6.  Add Flow to the Home Page

Now we add the screen flow on to the Home page of the salesforce organization. Follow these steps to add flow:

1.  Open the Home page from App Launcher.

2.  Click on the gear icon and then click on the Edit page option.

3.  Scroll down the page, you will be able to see the Lightning Web Component page which we created in the above steps.

4.  Drag and drop this Lightning Web Component onto the page layout.

5.  Click on the Save button at top right and Activate the page.

You will see the page like the below figure:

 

 

 

 

I hope this blog helped you!