Flow Invocable Apex – The number of results does not match

apexvisual-workflow

Hi I'm running into the following error when my scheduled flow does an Apex Action

The number of results does not match the number of interviews that were executed in a single bulk execution request.

The purpose of my apex callout is to take the Placement record that triggered the flow and locate all associated grandchild (Protest) records and return them so I can check if any are active and perform some additional logic. It's very possible that the one Placement can have multiple grandchild records and I need them all. I only run into the error when a Placement has 2+ Protests, if there's 0 or 1, there's no error.

Here is my code

    @InvocableMethod(label = 'Get Protest From Placement' description = 'Query all protests associated to a Placement. Return the list of protests associated to a Placement.')
    public static List<Protest__c> getProtestsFromPlacement(List<Id> placementIdList) {
        
        //created to hold return list of protests records
        List<Protest__c> protestsToReturnList = new List<Protest__c>();
        
        //query for associated protests
        List<Protest__c> protestsList = [SELECT Id, Closed__c From Protest__c WHERE Placement_Requirement__r.Placement__c IN :placementIdList];

        for(Protest__c protests: protestsList) {
            protestsToReturnList.add(protests);
        }
        return protestsToReturnList;
    } 

How can I fix this error? Thanks

Best Answer

Flows are bulkified, so you need to make sure the number of values that are returned match the number of inputs provided. Each return value will match one input value, which will match the number of flows that are being evaluated.

@InvocableMethod(label = 'Get Protest From Placement' description = 'Query all protests associated to a Placement. Return the list of protests associated to a Placement.')
public static List<List<Protest__c>> getProtestsFromPlacement(List<Id> placementIdList) {
    Map<Id, List<Protest__c>> protestsByPlacement = new Map<Id, List<Protest__c>>();
    List<List<Protest__c>> results = new List<List<Protest__c>>();
    for(Id recordId: PlacementIdList) {
        protestsByPlacement.put(recordId, new List<Protest__c>());
    }
    for(Protest__c record: [SELECT Closed__c, Placement_Requirement__r.Placement__c from Protest__c WHERE Placement_Requirement__r.Placement__c = :placementIdList]) {
        protestsByPlacement.get(record.Placement_Requirement__r.Placement__c).add(record);
    }
    for(Id recordId: PlacementIdList) {
        // Each return value must be unique, so we have to clone.
        results.add(protestsByPlacement.get(recordId).clone());
    }
    return results;
}