Loading
Automatizar sus procesos de negocio con Salesforce Flow
Iniciar un flujo desde Apex

Iniciar un flujo desde Apex

Los flujos iniciados desde Apex pueden incluir lógica de negocio compleja y gestión de errores mejorada, y pueden integrarse con sistemas externos de forma más efectiva. Este enfoque promueve la reutilización encapsulando lógica en flujos que se pueden llamar según sea necesario. También proporciona un mayor control sobre el contexto de ejecución y el orden de las operaciones. La combinación de Apex y flujo le ayuda a crear aplicaciones más potentes y flexibles que son más fáciles de mantener.

Nota
Nota Iniciar un flujo desde Apex como administrador de flujo utiliza la versión más reciente del flujo, independientemente del estado de activación.

Puede utilizar la clase Invocable.Action o la clase Flow.Interview para iniciar un flujo desde Apex. Considere las diferencias entre las dos clases.

  • Si utiliza la clase Invocable.Action para ejecutar flujos, los flujos se ejecutan en lotes con masificación, pero solo puede hacer referencia a flujos de forma dinámica. Proporciona un valor de cadena para el nombre del flujo que no proporciona integridad referencial. Este enfoque puede ser mejor cuando desea ejecutar flujos arbitrarios, pero no cuando está llamando a un flujo específico.
  • Para obtener integridad referencial, utilice la clase Flow.Interview para hacer referencia a flujos de forma estática. No puede empaquetar o implementar Apex sin que el flujo exista en la organización de destino, la implementación o el paquete. Sin embargo, la clase de Flow.Interview no se puede ejecutar en lotes utilizando masificación.

Los límites de Lenguaje de consulta de objetos de Salesforce (SOQL) y Lenguaje de manipulación de datos (DML) se aplican durante la ejecución del flujo. Consulte Límites de flujo por transacción en la Ayuda de Salesforce.

En los ejemplos, considere este flujo de muestra:

  • Nombre de API de flujo: MyFunFlow
  • El flujo tiene dos variables de texto disponibles para su entrada:
    • inputA
    • inputB
  • El flujo tiene una variable de texto disponible para el resultado:
    • outputVariable
  • El flujo tiene un elemento Asignación que concatena los valores de inputA e inputB y asigna el resultado a outputVariable

Ejecución de un único flujo iniciado automáticamente desde Apex con la clase Invocable.Action

Para ejecutar un flujo utilizando Invocable.Action, cree una instancia de la clase Invocable.Action utilizando el método createCustomAction(). Establezca los valores de variable de entrada para una o más instancias del flujo que desea ejecutar y luego ejecute el método invoke(). El método invoke() devuelve un objeto que puede leer cualquier error o salida que proporcione el flujo.

Con este enfoque, puede ejecutar múltiples instancias del mismo flujo para diferentes conjuntos de entradas.

/* Set the input variable values into a Map<String,Object> with each input as a key, and the input value you want to set as the value */
Map<String,Object> flowInputVariables = new Map<String,Object>();
flowInputVariables.put('inputA','hello');
flowInputVariables.put('inputB','world');

/* Put the input map(s) into a List. Each item in this list represents a flow interview that's invoked together in a single batch run that uses flow bulkification. You must use a list, even if you want to run just one instance of the flow. */
List<Map<String,Object>> flowInputs = new List<Map<String,Object>{ flowInputVariables };

/* Initialize the flow as an action with the Action Type 'flow' and the API name of the flow */
Invocable.Action flowAction = Invocable.Action.createCustomAction('flow','MyFunFlow');

/* Use the input parameters to prepare the invocations that will be invoked */
flowAction.setInvocations(flowInputVariables);

/* Invoke the flow, assigning the results to a list of Invocable.Action.Result */
List<Invocable.Action.Result> flowResults = flowAction.invoke();

/* Read the results and outputs of the invocation */
for (Invocable.Action.Result result : flowResults) {
	if (result.isSuccess() == false) {
		// This invocation failed! read what the errors are with getErrors()
		List<Invocable.Action.Error> errors = result.getErrors();
	} else {
		// Success! Read the outputs with getOutputParameters()
		Map<String,Object> outputValues = result.getOutputParameters();
		String myFlowOutput = (String)outputValues.get('outputVariable');
		System.debug('Result: ' + myFlowOutput);
	}
}

Los registros de depuración muestran:

> Result: Hello World

Ejecución de múltiples instancias de un flujo iniciado automáticamente con la clase Invocable.Action y una única función invoke()

/* Set the input variable values into a Map<String,Object> with each input as a key, and the input value you want to set as the value. */
Map<String,Object> flowInput1 = new Map<String,Object>();
flowInput1.put('inputA','hello');
flowInput1.put('inputB','world');

Map<String,Object> flowInput2 = new Map<String,Object>();
flowInput2.put('inputA','foo');
flowInput2.put('inputB','bar');

/* Put the input map(s) into a list. Each item in this list represents a flow interview invoked together in a single batch run that uses  flow bulkification . You must use a list, even if you want to run one instance of the flow only. */
List<Map<String,Object>> flowInputs = new List<Map<String,Object>();
flowInputs.add(flowInput1);
flowInputs.add(flowInput2);

/* Initialize the flow as an action with the Action Type 'flow' and the API name of the flow */
Invocable.Action flowAction = Invocable.Action.createCustomAction('flow','MyFunFlow');

/* Use the input parameters to prepare the invocations that will be invoked */
flowAction.setInvocations(flowInputs);

/* Invoke the flow, setting the result to a list of Invocable.Action.Result */
List<Invocable.Action.Result> flowResults = flowAction.invoke();

/* Read the results and outputs of the invocation */
for (Invocable.Action.Result result : flowResults) {
	if (result.isSuccess() == false) {
		// This invocation failed! Read what the errors are with getErrors()
		List<Invocable.Action.Error> errors = result.getErrors();
	} else {
		// Success! Read the outputs with getOutputParameters()
		Map<String,Object> outputValues = result.getOutputParameters();
		String myFlowOutput = (String)outputValues.get('outputVariable');
		System.debug('Result: ' + myFlowOutput);
	}
}

Los registros de depuración muestran:

> Result: hello world > Result: foo bar
> Result: foo bar

Ejecución de un único flujo iniciado automáticamente desde Apex con la clase Flow.Interview

Para ejecutar un flujo utilizando la clase Flow.Interview, cree una instancia del Flow.Interview utilizando el método createInterview() o una instancia estática de Flow.Interview.FlowApiName. Establezca las variables de entrada y luego ejecute el método start(). Tras ejecutar el método start(), puede leer los valores resultantes de cualquier variable de salida utilizando el método getVariableValue() en la instancia del Flow.Interview.

Solo puede ejecutar un Flow.Interview a la vez con enfoques dinámicos o estáticos.

Ejecutar el flujo de forma dinámica con Flow.Interview.createInterview()

/* Set the input variable values into a Map<String,Object> with each input as a key, and the input value you want to set as the value */
Map<String,Object> flowInputVariables = new Map<String,Object>();
flowInputVariables.put('inputA','hello');
flowInputVariables.put('inputB','world');

/* Initialize the flow using the API name of the flow and the list of inputs you've defined */
Flow.Interview myFlow = Flow.Interview.createInterview('MyFunFlow',flowInputVariables);

/* Invoke the flow, setting the result to a list of Invocable.Action.Result */
myFlow.start();

/* Read the results and outputs of the invocation */
String myFlowOutput = (String)myFlow.getVariableValue('outputVariable');

System.debug('Result: ' + myFlowOutput);
Result: hello world

Ejecutar el flujo de forma estática con Flow.Interview.FlowApiName

/* Set the input variable values into a Map<String,Object> with each input as a key, and the input value you want to set as the value */
Map<String,Object> flowInputVariables = new Map<String,Object>();
flowInputVariables.put('inputA','hello');
flowInputVariables.put('inputB','world');

/* Initialize the flow using the API name of the flow and the list of inputs you've defined. By using this mechanism, you are creating a static reference to the flow, meaning any deployment or packaging of this Apex  requires the flow to exist in the target org,deployment, or package */
Flow.Interview myFlow = new Flow.Interview.MyFunFlow(flowInputVariables);

/* Invoke the flow, setting the result to a list of Invocable.Action.Result */
myFlow.start();

/* Read the results and outputs of the invocation */
String myFlowOutput = (String)myFlow.getVariableValue('outputVariable');

System.debug('Result: ' + myFlowOutput);
> Result: hello world

Ejecución de flujos de pantalla en código personalizado

Desde Visualforce: ver Integrar un flujo en una página Visualforce

Desde un componente Lightning personalizado: ver Integrar un flujo en un componente Aura personalizado

 
Cargando
Salesforce Help | Article