Lightning Flow is one of the key automation tools on the Salesforce Platform, and it really brings together Developers and Admins.

Screen Flows allow you to create create rich, guided experiences for users where you can display, collect, and process data while Autolaunched Flows can process data behind the scenes. As a Developer, getting hands on with Flow can help accelerate your development time and create consistency around your user experience.

Flow overview

Before we get into the details of Screen Flows, we need to take a deeper look at the wider capabilities of Flow. Flow can be used to automate processes on the platform without having to dip into code. The same processes can however, also be enhanced with the use of code. There are two overarching types of flows that you should be aware of – Screen Flows, which guide the user in a wizard like fashion through multiple screens, and Autolaunched Flows,which can be run with no human intervention.

What makes Flow a great way for Admins and Developers to work together is its tight framework for completing coding-like tasks without having to write code. Unlike the other declarative automation tools on the platform, you can create collections of sObjects, loop through data, perform DML on large datasets, and even write complex queries – all of which would normally take a bit of code to perform. On top of this, flows can be extended with Lightning Web Components and Apex to help perform more complex tasks. You can even create sub-flows to extract complex logic and create reusable patterns to make your flows more and more extensible.

Getting started with Screen Flows

Each Screen Flow can have a number of screens that are built with Standard Flow Components and Custom Components. As mentioned earlier, these screens can consist of input fields for collecting data, rich text display of data, or event custom UI elements that you build using Lightning Web Components. Each of these screens can be strung together by declarative logic, queries, DML or even Apex transactions. To top it off, each flow can also have a number of input variables that allow you to provide context into the flow. For example, if the flow is rendered on a record detail page, you can pass in the record id that is part of the page context.

Custom screen components

One of the best ways to create a great experience is by enhancing flows with custom components. You can build Lightning Web Components the same way that you would for any lightning page and use them inside of a screen on a flow. All you have to do is add the target lightning__FlowScreen into your LWC’s configuration file. You can then expose any of the public properties in your LWC to the flow by adding a <property> tag into the targets configuration.

Let’s take a look at building a flow to help users gather consent from their contacts inside of Flow.

The Lightning component that we would like to include in the flow can be configured in the .js-meta.xml file of the Lightning Web Component.

<?xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>49.0</apiVersion>
    <masterLabel>Consent Capture Display</masterLabel>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__FlowScreen</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__FlowScreen">
            <property name="recordId" label="Record Id" description="Flow input field" type="String" role="inputOnly" />
            <property name="sObjectType" label="SObject Type" description="Flow output field" type="String" role="outputOnly" />
            <property name="individualId" label="Individual Id" description="Flow output field" type="String" role="outputOnly" />
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>

Once you drag the component into the Flow Builder Screen, you can modify the values of the properties that have been exposed. In this case, we can pass in the values of the questions that we would like to ask the user.

Getting started with Autolaunched Flows

As mentioned earlier, Autolaunched Flows run in the background and allow you to query records, loop through records and perform CRUD operations on records without having to write a line of code. However, just like Screen Flows, they can be extended with code to perform more complex actions.

The different variations of Autolaunched Flow really boil down to the trigger criteria that instantiate the flow. There are a number of different flavors when it comes to Autolaunched Flows that you should be aware of:

Autolaunched Flowsmust be triggered by processes, Apex classes, the REST API, custom buttons, custom links, or Visualforce pages

Record-Triggered Flows are tied to an object. Whenever a record from that object changes, the flow kicks in and allows you to make before-save changes to that record. This type of flow only supports Assignment, Decision, Get Records, and Loop Elements.

Schedule-Triggered Flows run from a schedule that is defined in setup. The flow runs as the Automated Process User so you must be mindful of permissions.

Platform Event-Triggered Flows run when a Platform Event message is received.

Building an Autolaunched Flow

As mentioned earlier, an ideal use case for an Autolaunched Flow would be the manipulation of a number of different related records. In this case, we can look at updating the opt-in status of a contact or lead each time they modify their preferences. There are a number of objects used in this, including the new consent management objects. We could use flow to query the related consent records to a Lead or a Contact each time the Email Opt-Out checkbox is set to true. The complexity comes with the relationship between the Lead and Contact and the Contact Point Type Consent Record as they are joined by an Individual.

  1. You would need to use an Autolaunched Flow that can accept a recordId parameter for each of the object types.
  2. Create two variables for storing the recordId of the record that triggered the flow, and one for the sObjectType.
  3. Add a decision point to determine which query needs to be performed.
  4. Query for the IndividualId on the Lead and Contact Records.
  5. Use an Apex Invocable Action to perform the complex process of updating the opt-outs.

Invocable Actions give developers an opportunity to write any complex logic in Apex and expose it into Flow Builder and Process Builder in the form of useful declarative building blocks. An Invocable Action starts with an Apex Class with a method that contains your logic, and a number of input and output parameters that allow the flow to communicate with the class. Similar to Triggers, invocable actions are bulkified and can handle multiple calls. This results in the parameters being expressed as Lists. The only catch here is that the output parameters cannot be used in Process Builder, only Flow. In order to make the action available, you must annotate the method with @InvocableMethod and you can supply an optional label, description and category.

Following on with our Consent Flow, we can use an Invocable method to update the opt-in status of multiple records based on an Individual Record Id passed into the action.

public with sharing class FlowEmailOptOut {
  
  // Annotate the method InvocableMethod and give it a label and description
  @InvocableMethod(
    label='Process Email Opt-out'
    description='Opt out an individual from all communications'
  )
  public static List<Response> execute(List<Request> requests) {

    List<SObject> sObjectsToOptOut = new List<SObject>();

    // Create a list to hold the response object
    List<Response> responses = new List<Response>();

    // Iterate over the request object that is passed into the method
    for (Request req : requests) {

      // Processs the request
      List<sObject> contacts = optOutContacts(req.individualId);
      sObjectsToOptOut.addAll(contacts);

      List<sObject> leads = optOutLeads(req.individualId);
      sObjectsToOptOut.addAll(leads);

      List<sObject> contactPointTypeConsents = optOutContactPointTypeConsent(req.individualId);
      sObjectsToOptOut.addAll(contactPointTypeConsents);

      update sObjectsToOptOut;

      // Add the response to the list
      Response res = new Response();
      res.totalUnsubscribes = sObjectsToOptOut.size();
      responses.add(res);
    }

    // Return the response to the flow
    return responses;
  }

  // ---------------------------------------

  // The request object that takes input from the flow
  public class Request {
    @InvocableVariable(
      label='Individual Id'
      description='The Id of the individual that is opt-ing out'
      required=true
    )
    public ID individualId;
  }

  // The response object that passes data to the flow
  public class Response {
    @InvocableVariable(
      label='Total Unsubscribes Processed'
      description='The number of records that have been marked as opt-out'
    )
    public Integer totalUnsubscribes;
  }

Let’s say that we needed to take our flow for processing opt-outs and extend it to notify our third party marketing system that someone had unsubscribed. That is exactly why external services were created! They allow you to create another building block for your Admins, but this time allowing them to callout to APIs that you designate. An external service takes an Open API Schema and Named Credentials and generates an Invocable Action that can be used in a flow as well as Process Builder.

You can learn more about getting started with external services on Trailhead.

Conclusion

Flow Builder gives Developers and Admins the tools they need to collaborate on process automation in a way that drives productivity and creates great user experiences. Whether you need to build an interactive user interface or process data in the background, Flow can help you build a collaborative solution. You can check out the code from consent capture on GitHub for the examples from this blog post as well as a number of screen components worth checking out.

Want to get hands-on with some awesome Flow Actions and Components? Check out the Automation Components sample app for examples of Invocable Actions, Lightning Web Components, and Flow Local Actions that can be installed and used directly in an Org.

Continue learning about Flow on Trailhead:

Build Flows with Flow Builder Trail
Automate Your Business Process with Lightning Flow Trail

Other resources:

Lightning Flow Developer Center
unnoficialsf.com – for lots of automation developer resources
Develop Components for Flow Screens
Invocable Method Developer Guide

About the author

Stephan Chandler-Garcia is a Senior Developer Evangelist at Salesforce. He focuses on Application development, Security and Communities. You can follow him on Twitter @stephanwcg

Please click here to read the original article as posted on Salesforce Developers Blog.

We source the web to bring you best Salesforce articles for our reader’s convenience. If you want to have this article removed, please follow guidelines at Digital Millennium Copyright Act (DMCA)..

LEAVE A REPLY

Please enter your comment!
Please enter your name here