Friday, December 29, 2023

How To Call Flows From Apex

 

today we are going to make the Flow and call it through apex code and a scheduled class, which calls the controller method to execute the flow.


Step 1: Understanding Flows and Apex

Salesforce Flows automate processes visually, while Apex is used for complex logic. Integrating them allows for more dynamic and powerful automation in Salesforce.

Step 2: Creating a Flow

  • Navigate to Flow Builder: In Salesforce, go to Setup > Process Automation > Flows.
  • Create a New Flow: Choose a flow type suitable for your use case, like Record-Triggered or Auto-Launched.
  • Design the Flow: Add elements such as decisions, assignments, and actions. For instance, create a flow that sends an email when a new lead is added.

Step 3: Preparing Apex Code

  • Open Developer Console: In Salesforce, navigate to the Developer Console.
  • Create a New Apex Class: Name it, for example, FlowController.
  • Import Namespaces: Use System.Flow statements to import necessary namespaces.
public class FlowController {
    // Class content goes here
}

4. Calling the Flow from Apex

  • Instantiate the Flow: In your Apex class, instantiate the Flow using System.Flow.Interview.
public class FlowController {
    public void callFlow() {
        // Set up Lead record as an example
        Lead l = new Lead(FirstName = 'Sapna', LastName = 'Chandani', Email = 'sapna.chandani@example.com', Phone = '8522256355', MobilePhone = '876545465', Company = 'ExampleCompany');
        insert l;
        
        // Prepare the Flow variables
        Map<String, Object> params = new Map<String, Object>();
        params.put('newLead', l);
        
        // Instantiate and start the Flow
        Flow.Interview.Your_Flow_Name yourFlow = new Flow.Interview.Your_Flow_Name(params);
        yourFlow.start();
    }
}
  • Ensure to replace Your_Flow_Name with the actual name of your Flow.
  • Schedulable Class: For automating the flow execution at scheduled intervals.
global class scheduledFlow implements Schedulable {
    global void execute(SchedulableContext sc) {
        FlowController fc = new FlowController();
        fc.callFlow();
    }
}

No comments: