July 8, 2024
In Salesforce development, integrating Apex with Flows allows for powerful automation and customization. One common scenario is passing complex data structures, such as wrapper classes, from Apex controllers to Flows. Let's explore how to achieve this seamlessly.
First, let's create a simple wrapper class in Apex that we'll use to pass data to our Flow.
public with sharing class FlowInvoker {
@AuraEnabled
public String
firstName;
}
This class defines a single property firstName
, which we will populate and pass
to a Flow instance.
Next, we'll create a Flow in Salesforce that will receive an instance of our FlowInvoker
class as an input variable.
Create a Flow (PassWrapperInFlow):
Create an Input Variable:
FlowInvoker
inputVariable
Create an Output Variable:
FlowInvoker
outputVariable
Add an Assignments element:
Add an Action element:
Save and Activate the Flow:
Create an additional Apex class with an invocable method to handle the output from the Flow.
public class FlowHandler {
public class MyWrapper {
@InvocableVariable
public String firstName;
}
@InvocableMethod
public static void handleFlowOutput(List<MyWrapper>
wrappers) {
for (MyWrapper wrapper : wrappers) {
System.debug('firstName: ' + wrapper.firstName);
}
}
}
Note: Ensure that the Flow and Apex classes are saved and activated properly before testing.
Now, let's invoke the Flow we created from an Anonymous Apex script. This script will instantiate our
FlowInvoker
class, populate its firstName
property, and pass it as an input to the Flow.
FlowInvoker wrapper = new FlowInvoker();
wrapper.firstName = 'TestfirstName';
Map<String,
Object> inputVariables = new Map<String, Object>();
inputVariables.put('inputVariable',
wrapper);
Flow.Interview myFlow = Flow.Interview.createInterview('PassWrapperInFlow',
inputVariables);
myFlow.start();
FlowInvoker outputValue =
(FlowInvoker)myFlow.getVariableValue('outputVariable');
System.assert(false, 'Output Value: ' +
outputValue);
This script will print the outputVariable
from the Flow, ensuring that the data
has been passed and processed correctly.
By following these steps, you can pass complex data structures from Apex to Flows in Salesforce, enhancing your automation capabilities and making your processes more dynamic and robust.