Using Lightning Component In Flows

Introduction :

In this post, I am going to show how to use the lightning component in the flow. the example I am taking hers is search contact based on user inputs like the user will enter contact information and once the form is submitted from the flow, we will fetch the flow input and passing it the lightning component to get the contacts. To use a custom Lightning component in flow screens, configure the component and it is designed to the resource so that they’re compatible with the Cloud Flow Designer.

 Apex Class 

public class ContactsListController {
    @AuraEnabled
    public static List<contact> getContacts(String firstName,String lastName ,String email ,String phone) {
        List<contact> results = Database.query(
            'Select Id, FirstName, LastName, Title, Email,MobilePhone FROM contact where FirstName =\''+firstName +'\' OR LastName =\''+lastName+'\' OR Email=\''+email+'\' OR MobilePhone =\''+phone+'\'');
        return results;  
    }
    
}

Lightning Component

The below is the lightning component which we will use in cloud flow designer. This component will collect the input values from the flow and pass it the controller to fetch the contacts

<aura:component implements="lightning:availableForFlowScreens" access="global" controller="ContactsListController">
    <aura:attribute name="firstName" type="String" default="" access="global" />
    <aura:attribute name="lastName" type="String" default="" access="global" />
    <aura:attribute name="email" type="String" default="" access="global" />
    <aura:attribute name="phone" type="String" default="" access="global" />
    <aura:attribute name="rows" type="Contact[]" default="" access="global" />
    <aura:handler name="init" value="{!this}" action="{!c.init}" />
    <table class="slds-table slds-table--bordered slds-table--striped">
        <thead>
            <tr>
                <th scope="col"><span class="slds-truncate">FirstName</span></th>
                <th scope="col"><span class="slds-truncate">Last Name</span></th>
            </tr>
        </thead>
        <tbody>
            <aura:iteration items="{!v.rows}" var="row">
                <tr>
                    <td>{!row.FirstName}</td>
                    <td>{!row.LastName}</td>
                </tr>
            </aura:iteration>
        </tbody>
    </table>
    
    
</aura:component>
({
    init : function(component, event, helper) {
        var action = component.get("c.getContacts");
        action.setParams({
            firstName : component.get('v.firstName') ,
            lastName : component.get('v.lastName') ,
            email : component.get('v.email') ,
            phone : component.get('v.phone') 
        });
        
        action.setCallback(this, function(a) {
            if (a.getState() === "SUCCESS") {
                component.set("v.rows",a.getReturnValue()); 
            } else if (a.getState() === "ERROR") {
                $A.log("Errors", a.getError());
            }
        });
        
        $A.enqueueAction(action); 
    },
    
    
})

design.resource

<design:component >
    <design:attribute name="firstName" label="firstName" />
    <design:attribute name="lastName" label="lastName" />
    <design:attribute name="email" label="email" />
    <design:attribute name="phone" label="phone" />
    
</design:component>

Flow 

Now create a simple flow as shown below. I create a flow with multiple screens but you can create a single screen. Evey screen is having only one text field line first name, last name, email, and phone. The final is screen is the place where I am invoking the lightning component.

The below image shows how to call the lightning components from the flow designer. Use Lightning Component Extension 

configuree the input and output variable as shown below 

Add it the Lightning Record page. Now you can see your flow as shown below.  

You can able to search the contacts from the flow screen as shown below after entering the first name, last name, and email and phone.

 

 

Lightning Components for Flow Screens

In this blog, i am going to explain how to create a lightning component to use in cloud flow designer.Make your custom Lightning components available to flow screens in the Cloud Flow Designer by implementing the lightning: availableForFlowScreens interface. After defining the component you need to add design resource to your component bundle. A design resource describes the design-time behavior of a Lightning component—information that visual tools need to allow adding the component to a page or app. It contains attributes that are available for admins to edit in the Cloud Flow Designer.

Step1:- Create a Component 

create a new lightning component as shown below. In order to use the component in cloud flow designer, you need to implement lightning:availableForFlowScreens interface.

<aura:component implements="lightning:availableForFlowScreens" access="global">
    <aura:attribute name="greeting" type="String" default="Hello" access="global" />
    <aura:attribute name="subject" type="String" default="World" access="global" />

    <div style="box">
      <span class="greeting">{!v.greeting}</span>, {!v.subject}!
    </div>
</aura:component>

Add the flowing code to designer resource for the above component.

<design:component label="Componet for Flow">
    <design:attribute name="greeting" label="greeting"  default="Hello"  />
    <design:attribute name="subject" label="subject" default="World"  />
</design:component>

 

Step 2: Create a flow 

Open the Cloud Flow Designer From the Setup Drag the appropriate screen element onto the canvas as snow below.

Now from the Add Field Section Drap and Drop the lightning component from the extension section as shown below

Now add the Unique name and then select the lightning compoent from  the dropdown 

Create an input and output variable  as shown below

 

  • Now set starting element to the flow.
  • Save the flow
  • Activate the flow

 

Step3: Add to the Salesforce UI 

Now you can add the flow the Salesforce user interface . in this example I am just adding the flow to the opportunity record page. Go to the opportunity records on lightning and edit the page drag and drop the flow component to the page as shown below

Save the record page.Now you can go to opportunity records to see the lightning component output that was invoked from the flow as shown below

 

 

 

 

Control Flow Behavior with Lightning Component

Introduction 

In this blog post is the extension for this two posts Salesforce Flow Actions and Invoking Flow From Lightning Component. In this post, I am going to explain how to set up the flow with input and output variable and finish behavior from the Lightning component.This is more or less similar to control the flow behavior from the visualforce. I am going to reuse the same flow which I created for the  Salesforce Flow ActionsBut create a different input and output variable to store the values instead of using screen input variable to store the value.

Go to developer console  and create a new Lightning component with below code

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    
    <aura:handler name="init" value="{!this}" action="{!c.init}"/>
    <lightning:flow aura:id="flowId" onstatuschange="{!c.handleStatusChange}" />
       
</aura:component>

Here is the basic code for the controller.

({
    init : function (component) {
        var flow = component.find("flowId");
        flow.startFlow("SOinser");
    },
    handleStatusChange : function (component, event) {
        
    },
})

Set Flow Variables

 When you embed a flow in a Lightning component, give the flow more context by initializing its variables, sObject variables, collection variables, or sObject collection variables. In the component’s controller, create a list of maps, then pass that list to the startFlow method on the component. Now, let’s start modifying the code to pass the default values when the flow is launched from the component as shown below.
({
    init : function (component) {
        var flow = component.find("flowId");
        var inputVariables = [
            { name : "salesorderid", type : "String", value: "1234" }, 
            { name : "poid", type : "String", value:"PO#123" },
            { name : "orderamountid", type : "Currency", value:9000 },
            { name : "disid", type : "Number", value:12 },
            { name : "shipingid", type : "Currency", value: 120 }
        ];
        flow.startFlow("SOinser" , inputVariables);
    },
    handleStatusChange : function (component, event) {
        
    },
})

In the above controller code, we have used inputVariables array to hold the default values and passed it to the startFlow method as the second argument. You can see the flow has populated the values as shown below.

Even if you would like to populate a value form the apex class you will be able to do it as shown below.Create a server-side apex controller as shown below  and refer from the component

public class TestFlow {
    @AuraEnabled
    public static Account getAccountId(){
        
        return [Select Id , Name from Account Limit 1];
    }
    
}

In the Component controller, you can modify the code as shown below. It’s going to fetch server-side data on the initialization of the component and populate it the flow as an input variable.

 var action = component.get("c.getAccountId");
        action.setCallback(this, function(response) {
        	 var inputVariables = [
               {
                  name : "account",
                  type : "SObject",
                  value: response.getReturnValue()
          	     }
                 
            ];
                    flow.startFlow("myFlow", inputVariables);

            
        });

Below table shows some of the data types and its valid values format.

Flow Variable Type Type Valid Values
Text String { name : “textVar”, type : “String”, value: “Passing String” }
Number Number          { name : “numVar”, type : “Number”, value: 30 },
Currency Currency          { name : “cncyVar”, type : ” Currency “, value: 30.12 },
Boolean Boolean          { name : “boolVar”, type : ” Boolean “, value: true },
Date Date          { name : “dateColl”, type : “String”, value: [ “2016-10-27”, “2017-08-01” ] },
Date/Time DateTime          { name : “dateTimeColl”, type : “String”, value: [ “2016-10-27”, “2017-08-01:00:00:00:T” ] },
sObject SObject 1 .{ name : “account”, type : “SObject”, value: {“Id” : component.get(“v.accountId”),”Rating” : “Warm”}}

2. { name : “account”, type : “SObject”, value:                  value: response.getReturnValue()}}

Get Flow Variable

Even you can able to get the Flow variable values can be displayed or referenced in a Lightning component . Once you’ve embedded your flow in a custom Lightning component, use the onstatuschange action to get values from the flow’s output variables. Output variables are returned as an array. Now here is the mockup code that will display the result to component from the flow variables

 
    <aura:attribute name="salesorderid" type="String" />
    <aura:attribute name="poid" type="Decimal" />
    <aura:attribute name="orderamountid" type="Currency" />
    <aura:attribute name="disid" type="Number" />
    <aura:attribute name="shipingid" type="Currency" />
   
    <p><lightning:formattedText value="{!v.salesorderid}" /></p>
    <p><lightning:formattedText  value="{!v.poid}" /></p>
    <p><lightning:formattedText value="{!v.orderamountid}" /></p>
    <p><lightning:formattedText  value="{!v.shipingid}" /></p>

Now from the controller handleStatusChange  method you can able get the flow status by calling     event.getParam(“status”)  and   event.getParam(“outputVariables”)  return the output variables   as shown below .

 handleStatusChange : function (component, event) {
        if(event.getParam("status") === "FINISHED") {
            console.log('Runing');
            var outputVariables = event.getParam("outputVariables");
            console.log(outputVariables) ;
            var outputVar;
            for(var i = 0; i < outputVariables.length; i++) {
                outputVar = outputVariables[i];
                if(outputVar.name === "salesorderid") {
                    component.set("v.salesorderid", outputVar.value);
                }  
            }
        }
        
    }

Here is display result value console for the same.

Set Finish Behavior

By default, when a flow user clicks Finish, the component starts a new interview and the user sees the first screen of the flow again. However, you can shape what happens when the flow finishes by using the onstatuschange action. To redirect to another page, use one of the force:navigateTo* events such as force:navigateToObjectHome or force:navigateToUrl as shown below on handleStatusChange controller method.

 if(outputVar.name === "redirect") {
                    var urlEvent = $A.get("e.force:navigateToSObject");
                    urlEvent.setParams({
                        "recordId": outputVar.value,
                        "isredirect": "true"
                    });
                    urlEvent.fire();
                }
            }

 

 

Invoking Flow From Lightning Component

Introduction

In this blog, I am going to explain how to include a flow in your Lightning component.what I am going to do here is I am creating a Lightning component that will contain flow to create a sales order from the account.

Create a Flow 

Now I am going to create a flow to insert the sales order from the flow screen. We are using two flow elements in this example namely screen and record create elements.Go to flow from the setup menu and click on the new flow . from the Palette drag and drop the screen element into the flow  as shown below

From the add field sections add the different filed to store the sales order data into the object as shown below and click OK after adding all the fields labels

Now drag and drop the records create element flow to insert data into the sales order object. Select the Sales Order object from the Assignments 

perform the field mappings from  the screen input as shown below

Connect the flow element and set the screen element as flow starting element.

Save the flow as shown below and activate the flow.

Create a lighting component 

Go to developer console and create a new Lightning component “Flow Demo”  with the below code.

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
	<aura:handler name="init" value="{!this}" action="{!c.init}" />
    <lightning:flow aura:id="flowId" />
</aura:component>

And Controller is here below.

({
    init : function (component) {
        // Find the component whose aura:id is "flowId"
        var flow = component.find("flowId");
        // In that component, start your flow. Reference the flow's Unique Name.
        flow.startFlow("SOinser");
    },
})

Understand the code

  • We used <lightning: flow> component to add the flow onto the UI with aura: id.
  • From the controller init method get the flow aura: id of the lightning: flow component to set the flow.
  • Invoke your flow from flow.startFlow(“SOinser”) method of component  .