How to use an Apex Trigger to start an Autolaunched Flow and pass in a collection of new records

after-triggercollection-variablevisual-workflow

I have an object that receives frequent imports. We tried a record-triggered flow to handle after-save processing of related records, but we're hitting limits with import files >100 records. Record-triggered flow interviews only run on one record, but autolaunched flows can work on collections.

What I want to do is use an Apex trigger to launch a Flow and pass in the collection of new records. This way the Flow can process the new records in loops and perform the DML at the end on the whole batch instead of multiple DML calls per new imported record.

Here is my current code:

trigger InboundReferralTrigger on Inquiry__c (after insert) {

    List<Inquiry__c> inputInboundReferrals = trigger.new;
    
    Flow.Interview.Inbound_Referral_Apex_Triggered_Flow myFlow = new Flow.Interview.Inbound_Referral_Apex_Triggered_Flow(inputInboundReferrals);
    myFlow.start();         
}

And here is the error message I receive when I try to deploy:

Constructor not defined:
[Flow.Interview.Inbound_Referral_Apex_Triggered_Flow].(List<Inquiry__c>)
(5:66)

I'm using this documentation as the starting point for my code:

Thanks for any help you can provide!

Best Answer

If you look closely at the documentation you linked, you'll see that they're specifically using Map<String, Object> inputs = new Map<String, Object>(); to provide data to the flow where:

  • key of map = name of the input variable in the flow
  • value of key = data set in the input variable
{
  Map<String, Object> inputs = new Map<String, Object>();
  inputs.put('AccountID', myAccount);
  inputs.put('OpportunityID', myOppty);
  
  Flow.Interview.Calculate_discounts myFlow = 
    new Flow.Interview.Calculate_discounts(inputs);
  myFlow.start();
}

As such, you'll want to pass your list of data as the value in a map that has a key that matches your collection variable name in Flow

trigger InboundReferralTrigger on Inquiry__c (after insert) {

    List<Inquiry__c> inputInboundReferrals = trigger.new;
    //Create map of input variables/values for flow
    Map<String, Object> params = new Map<String, Object>();
    params.put('YourCollectionVariableName', inputInboundReferrals);
    
    Flow.Interview.Inbound_Referral_Apex_Triggered_Flow myFlow = new Flow.Interview.Inbound_Referral_Apex_Triggered_Flow(params);
    myFlow.start();         
}

If you're going through the trouble of using apex trippers to call flows - you may want to consider doing it all in apex. Especially, if you're iterating a lot in that flow - be aware of other limitations you could run into regarding number of iterations exceeded (limit of 2000 executed elements at run time). At the very least, you may want to consider filtering your records before calling the flow if possible.