function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Adelchi PelizzoAdelchi Pelizzo 

Flow Error: The number of results does not match ....

I am getting this error: The number of results does not match the number of interviews that were executed in a single bulk execution request.
Here is the apex class I am using, I want to store list<string> data from a json file into a flow variable:
global class par{

    global static List<string> l = new list<string>();
    
@InvocableMethod(label='Get Map' description='Returns the values of Maps')
    global static List<String> CallMap(){
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=AIzaSyBOyIQi54LMykmzSOvCuQ2naVvVQEsEfHw');
        req.setMethod('GET');
        Http http = new Http();
        HTTPResponse res = http.send(req);
        JSONParser parser = JSON.createParser(res.getBody());
        while (parser.nextToken()!= null)
        {
            if ((parser.getCurrentToken() == JSONToken.FIELD_NAME))
            {
                    string fieldName = parser.getText();
                    parser.nextToken();
                if(fieldName == 'place_id')
                {
                    string place = parser.getText();
                    system.debug(place);
                    l.add(place);
                	parser.nextToken();
                }else if(fieldName == 'status')
                	{
                    string status = parser.getText();
                    system.debug(status);
                    l.add(status);
                    }
        	}
    	}
        return l;
    }
}



 

 
NagendraNagendra (Salesforce Developers) 
Hi Adeichi,

I ran into a similar issue. Basically, the size (and possibly type?) of the return value needs to match the input value. I resolved the issue by returning void. Because flows run asynchronously, it seems like a best practice to always return void; then in unit tests, query for any expected results after the action has executed. 

Please mark this post as solved if it helps.

Best Regards,
Nagendra.P
Adelchi PelizzoAdelchi Pelizzo
Thank you for copy and paste: http://salesforce.stackexchange.com/questions/116249/what-does-this-flow-error-mean-the-number-of-results-does-not-match-the-number
Naveen KNNaveen KN
I got the same issue. Remember that size of the list you pass to the Apex code should be similar to the size of the list you return to the flow  
Jason Kuzmak 12Jason Kuzmak 12

Why though? I'm trying to get multiple records that all return as results queried from a single value. The only reason I'm passing my invocable method a list at all is because I have to. 

While trying to build a flow that grabs and builds the correct list of checklist questions for a particular machine model that's being serviced, my query string is:

'Select Id, Checkbox_Options__c, Checklist_Template_Section__c, Objective__c, Required__c, Sort_Order__c From Checklist_Template_Item__c Where Applies_To__c Includes(:searchModel)'   

SearchModel can only be a single model of machine that a field tech is servicing.

Trent Foor 5Trent Foor 5
We ran into the same issue, but were able to rectify it without having to return void. As others have stated, the size of the output collection needs to match the size of the inptut collection.
Our specific issue was related to Contacts. We were having issues where Contact records were being created at the same time. Because of this, an invocable method we were utilizing was being called once, but had multiple elements. Our method was processing the list but we were only returning 1 element. This caused the above error. Our solution for this was looping over the intial list. If the size of the collection is above 1, we are returning a result for each element. 
Richard Fosu 12Richard Fosu 12
Hi Trent, Could you show an example of your code. I'm playing around with invocablemethods from a flow and have hit the same issue. My simple test is to retrieve a list of Contacts from a User inputted Account Name, as you've highlighted the issue is with the collection size I'm passing into the class. Could you illustrate further what you mean by looping over the collect?
David Tissen 7David Tissen 7
After running into same Issue und analyzing the Issue this is the aswer:
1. Issue is mostly caused by Flows and Processes invoking an "Invocable Method".
2. Flows and Processes REQUIRES the same AMOUNT of Results as Requests which where given to the Invocable Method.
3. The Return Type must NOT be the same as the Request type.
4. The Return Type VOID is NOT VALID for Flows and Processes.
5. Workaround for Users which give back LESS Results than Requests: Input Parameter is List<List<WHATEVERYOUWANT>> and Response is also LIST<LIST<WHATEVERYOUWANT>>. The clou is to use always the inner List and add all Requests and Reponses into the inner List. The outer List contains allways the inner List. This results in the same Amount of Requests and Responses (1 List with 1 List)

Last Point Credits go to another User:https://developer.salesforce.com/forums/?id=9062I000000QwROQA0
David Roberts 4David Roberts 4
Thanks, everyone.
I had the same error message.
It's not that the size of input and output are the same. It just needs to be a list of lists.
I didn't need to send anything into the method. Using a List<List<>> for the return was necessary.
@InvocableMethod(label='Get Group Member\'s Email Addresses' description='Returns the list of email addresses for the group.')
    public static List<List<String>> invGetGroupEmails(){
        String uEmail;
        List<string> lstGroupEmails= new List<string>();
        List<List<String>> lstReturn = new List<List<String>>();
        
        List<User> lstGroupMembers = [SELECT id, Name, Email, isactive, profile.name, userrole.name, usertype FROM User 
					WHERE id IN (SELECT userorgroupid FROM groupmember WHERE group.Name = 'Your_Group_Name_Here')];
        if ( !lstGroupMembers.isEmpty() ) {
            for (User gm : lstGroupMembers) {
                uEmail = gm.Email;
                lstGroupEmails.add(uEmail);
                //system.debug('uEmail = '+uEmail);
            }//next

        }//endif not empty
        system.debug('size of list = '+lstGroupEmails.size());
        lstReturn.add(lstGroupEmails);
        return lstReturn; 
    }//invGetGroupEmails


I then expanded it to send in the group Ids:
public class ProjectAutomationActions2 {
    @InvocableMethod(label='Get Multiple Group Member\'s Email Addresses' description='Returns the list of email addresses for multiple groups.')
    public static List<List<String>> invGetMultipleGroupEmails(List<List<Id>> lstLstGroupIds){
        
        List<Id> lstGroupIds = lstLstGroupIds.get(0);
        
        List<String> lstResults = new List<String>();
        List<User> lstGroupMembers = [SELECT id, Name, Email, isactive, profile.name, userrole.name, usertype
                    FROM User 
                    WHERE id IN (SELECT userorgroupid FROM groupmember WHERE group.Id IN :lstGroupIds)];
        system.debug('result size = '+lstGroupMembers.size());
        system.debug('member records = '+lstGroupMembers);
        if ( !lstGroupMembers.isEmpty() ) {
            for (User gm : lstGroupMembers) {
                lstResults.add(gm.Email);
                system.debug('uEmail = '+gm.Email);
            }//next
        }//endif not empty
        system.debug('size of email list = '+lstResults.size());
        
        List<List<String>> lstLstResults = new List<List<String>>();
        lstLstResults.add(lstResults);
        return lstLstResults; 
    }//invGetMultipleGroupEmails
}

I agree with 'David Tissen 7', Kudos to 'Jason Kuzmak 12' for his post https://developer.salesforce.com/forums/?id=9062I000000QwROQA0
Rishab MishraRishab Mishra
Hi all,
I'm Also getting the same error when i tries to find the object name in my code
 
public with sharing class GetObjectName {
    @InvocableMethod
    public static List<List<string>> returnObjectName(List<string> recordIdStrings){
        // object Ids to return
        List<string> objectNames = new List<string>();
        // get record name
        Id recordId = Id.valueOf(recordIdStrings[0]);
        String objectName = recordId.getSobjectType().getDescribe().getName();
        // add object name to list
        objectNames.add(recordId.getSobjectType().getDescribe().getName());
        // return
        return objectNames;
    }
}

and uses this apex in one of my flow. Storing the return value in a text variable.
Rishab MishraRishab Mishra
Updated my above code snippet
public with sharing class GetObjectName {
    @InvocableMethod
    public static List<string> returnObjectName(List<string> recordIdStrings){
        // object Ids to return
        List<string> objectNames = new List<string>();
        // get record name
        Id recordId = Id.valueOf(recordIdStrings[0]);
        String objectName = recordId.getSobjectType().getDescribe().getName();
        // add object name to list
        objectNames.add(recordId.getSobjectType().getDescribe().getName());
        // return
        return objectNames;
    }
}

 
David Roberts 4David Roberts 4
I finally figured out the answer to Jason's question, "Why?":
After encountering the issue again in a batch process that was causing an account flow to run, I tried all the above solutions again. Then, almost by accident, I checked the size of the List<List<>> and found mutliple entries when the batch was running. I bulkified my apex class and solved the problem.
So, when a batch process runs, it passes multiple values into the flow. Your flow may only describe one value being returned but the batch will return multiple values.
Two days of head-scratching well spent.
Mattia Castellano 8Mattia Castellano 8
Hi, I had the same issue, the problem was when multiple items are processed.
In this case when the flow calls the APEX function what happens is that in input you have a list of values, so you have to manage it.

In my case, I solve it by adding a for each on the input list and doing all the operations for each element of the list.
David Roberts 4David Roberts 4
Or it may be that the input list is empty so use an 'if' statement as described by Keiji in https://trailblazers.salesforce.com/answers?id=9064S000000DfawQAC
if(!inputlist.isEmpty()){

   //do stuff to input list
   return lstLstReturns;

} else return null;
//endif inputparms has values

 
Tonnie StapTonnie Stap
@All,

Dear colleagues,

I am experiencing the same problem with some Apex code already present in our org. A flow will pass one object to the InvocableMethod and everything works fine. However when multiple objects trigger the flow the Apex requests are bulkified and  it will return the wrong number of results, it should be just 1 list of lists. I have tried the above list <list> additions but my knowlegde of Apex is not good enough to make all the nessecary adjustments. Can anyone correct this Apex code so it will run when called with multiple inputs?

Thanks in advance, your help is greatly appreciated.

public with sharing class HashAction {

  @InvocableMethod(label = 'Get hashed value')
  public static list < Result > getHashedValue(list < Request > requests) {

    list < Result > results = new list < Result >();

    if (requests != null && requests.size() > 0) {

      Request request = requests.get(0);
      results.add( new Result( getHash( request.getValue() ) ) );
    }

    return results;
  }


  public class Request {

    @InvocableVariable(label = 'Value to hash' required = true)
    public String input;

    public String getValue() {
      return this.input;
    }
  }


  public class Result {

    @InvocableVariable(label = 'Hashed value')
    public String hash;

    public Result(String hash) {
      this.hash = hash;
    }
  }


  public static String getHash(String input) {

    if (input == null) {
      return null;
    }

    return EncodingUtil.urlEncode( EncodingUtil.base64Encode( Crypto.generateDigest( 'SHA-256', Blob.valueOf(input) ) ), 'UTF-8' );
    // return EncodingUtil.base64Encode( Crypto.generateDigest( 'SHA-256', Blob.valueOf(input) ) );
  }
}