Skip to content

How to call an Invocable method in Apex

The Problem

I had to call an existing Invocable class from the Execute Anonymous window to reuse its method.

The Solution

Firstly, ensure you have the existing Invocable class ready. Here's an example of what it might look like:

public class MyInvocableClass {
   public class Requests {
       @InvocableVariable(label='Records for Input' description='sObject Records to assign' required=true)
       public List<SObject> inputCollection;

       @InvocableVariable(label='Query to assign users' description='Query will be used to retrieve users' required=true)
       public String query;

   public static void execute(List<Requests> requestList) {
       for (Requests request : requestList) {
           //...perform desired actions

Next, you'll need to execute some code in the Execute Anonymous window to interact with this class. Here's how:

// Define a query to retrieve tasks
List<Tasks> listTasks = [SELECT Id FROM Tasks WHERE Subject = 'Need to change users'];

// Define a query to retrieve active users
String queryUsers = 'SELECT Id FROM Users WHERE IsActive = true';

// Prepare a list of requests for the Invocable method
List<MyInvocableClass.Requests> listRequests = new List<MyInvocableClass.Requests>();

// Populate the request object
MyInvocableClass.Requests requests = new MyInvocableClass.Requests();
requests.inputCollection = listTasks;
requests.query = queryUsers;

// Call the Invocable method

This approach allows you to reuse code from Invocable classes.


For more information on Invocable methods, refer to the Salesforce developer documentation.