Newer Version Available

This content describes an older version of this product. View Latest

Associate Flows to Records with Apex

If you want to control how you trigger the creation of a RecordAction, you can use Apex to associate flows to records. The RecordAction object is exposed as a standard object in Apex and you can trigger it before DML operation, on delete or undelete, and even provide custom error handling.

RecordAction is available in API version 42.0 and above.

Note

Here are some scenarios that Apex better accommodates:
  • Triggering before Data Manipulation Language (DML) operation, rather than after
  • Triggering on delete and undelete DML
  • Validating data before the action is run
  • Custom error handling
  • Partial completion rather than complete failure

Example

This example uses an Apex class and trigger pair to demonstrate how to associate a flow to a newly created account that satisfies a specific criteria. In the class, a method is defined that takes in a list of accounts and creates a new RecordAction for each of them, setting the new account as the RecordId and the FlowDefinition as an active flow. The trigger is called after the insert of an account record, and if the criteria (type is ‘Customer’) is satisfied, then the class method described above is executed and adds the defined flow to the new account.

Apex Class

1public class RecordActionHandler {
2    public static void addNewCustomerFlow(Account[] accts) {
3        RecordAction[] recordActions = new List<RecordAction>();
4        for (Account a : accts) {
5            RecordAction ra = new RecordAction(RecordId=a.Id, FlowDefinition='New_Customer_Flow', Order=1);
6            recordActions.add(ra);
7        }
8        
9        try {
10            insert recordActions;
11        } catch (DMLException e) {
12            System.debug('An unexpected error has occurred: ' + e.getMessage());
13        }
14    }
15}

Apex Trigger

1trigger RecordActionTrigger on Account (after insert) {
2    Account[] customerAccounts = new List<Account>();
3    for (Account a : Trigger.new) {
4        if (a.Type == 'Customer') {
5            customerAccounts.add(a);
6        }
7    }
8    RecordActionHandler.addNewCustomerFlow(customerAccounts);
9}