Invocable Actions in Salesforce
Table of contents
- Invocable Method examples in Salesforce ?
- Frequently Asked Questions
- Bulk data processing within Invocable Methods to ensure they are bulk-safe?
Invocable Actions are a powerful feature in Salesforce that allow developers to create reusable actions or methods that can be invoked from various parts of the Salesforce ecosystem, such as process builders, flows, or even external applications via REST API calls. The key idea behind Invocable Actions is to encapsulate business logic in a way that it can be easily reused across different automation tools within Salesforce, without the need to write the same logic multiple times.
Explore our job-oriented Salesforce course career building program for beginners.
Here’s how they work: Invocable Actions are defined in Apex, which is Salesforce’s proprietary programming language. When you define an Invocable Action, you write an Apex class and annotate it with the @InvocableMethod annotation. This annotation tells Salesforce that the method can be called from outside the Apex class itself, specifically from process builders, flows, or API calls. You can pass input parameters to the Invocable Method from these calling contexts, and you can also define return types to send data back to the calling context.
Read more: Strings in Salesforce Apex
The process of invoking these actions is straightforward. In a flow, for example, you would add an action element and select the Invocable Action you wish to use. You then map any required inputs into the action and handle outputs as needed. This allows for complex business logic to be executed as part of a flow, enhancing the automation capabilities within Salesforce.
One of the strengths of Invocable Actions is their flexibility. Since they can accept lists as inputs and outputs, a single call to an Invocable Action can process multiple records at once, making them highly efficient for bulk operations. This is particularly useful when working with large datasets or when performing operations that affect multiple records in a single transaction.
Read more: Latest Salesforce interview questions and answers.
In summary, Invocable Actions in Salesforce are a robust feature for developers to encapsulate business logic in reusable units that can be easily integrated into Salesforce’s automation tools. They offer a way to streamline processes and ensure consistency in business logic implementation across the Salesforce platform, making them an essential tool in the Salesforce developer’s toolkit.
CRS Info Solutions offers real-time Salesforce course for beginners designed to equip learners with practical knowledge and industry skills in Salesforce. Enroll for demo today.
Invocable Method examples in Salesforce ?
Let’s dive into an example of how an Invocable Method can be implemented in Salesforce. This example will demonstrate a simple use case where we create an Invocable Method to update a custom field on Contact records based on certain criteria.
Read more: Arrays in Salesforce Apex
Scenario:
Suppose we have a custom field on the Contact object named Custom_Status__c. We want to create an Invocable Method that updates this field for a list of contacts based on some input parameters. The method will mark the Custom_Status__c field as “Active” for contacts that meet our criteria.
Step 1: Define the Invocable Method
First, we define an Apex class with an Invocable Method. This method takes a list of contact IDs as input and updates the Custom_Status__c field for those contacts.
public class ContactStatusUpdater {
// Define a class to hold the input parameters for the InvocableMethod
public class Request {
@InvocableVariable(required=true)
public Id contactId;
}
// Define a class to hold the output of the InvocableMethod
public class Response {
@InvocableVariable
public String message;
}
@InvocableMethod(label='Update Contact Status' description='Updates the custom status field on Contact records')
public static List<Response> updateContactStatus(List<Request> requests) {
// Prepare a list to hold the contacts to update
List<Contact> contactsToUpdate = new List<Contact>();
// Iterate over each request to prepare the contact records for update
for (Request req : requests) {
Contact contact = new Contact(Id = req.contactId, Custom_Status__c = 'Active');
contactsToUpdate.add(contact);
}
// Update the contacts in the database
try {
update contactsToUpdate;
// Prepare the response
List<Response> responses = new List<Response>();
for (Request req : requests) {
Response res = new Response();
res.message = 'Contact with ID ' + req.contactId + ' updated successfully.';
responses.add(res);
}
return responses;
} catch (DmlException e) {
// Handle the exception and prepare an error response
List<Response> errorResponses = new List<Response>();
Response errorRes = new Response();
errorRes.message = 'An error occurred: ' + e.getMessage();
errorResponses.add(errorRes);
return errorResponses;
}
}
}
Read more: collections in Salesforce Apex
Explanation
- Request Class: This inner class is used to define the input parameters for the Invocable Method. Each
Requestinstance represents a set of parameters for one invocation of the method. Here, we’re passing the Contact ID. - Response Class: This inner class is used to define what the Invocable Method returns after execution. In this case, we’re returning a message indicating the success of the operation.
- @InvocableMethod: This annotation makes the
updateContactStatusmethod invocable from Salesforce automation tools like Process Builder or Flow. It takes a list ofRequestobjects as input and returns a list ofResponseobjects. - Processing: The method iterates through the list of request objects, constructs
Contactrecords with the updatedCustom_Status__cfield, and attempts to update these records in the database. It then prepares a response based on the outcome of the operation.
Usage
This Invocable Method can now be called from a Flow, Process Builder, or even from external systems (via Salesforce’s REST API, if properly exposed), allowing for flexible and powerful automation scenarios. This example simplifies the process of updating a specific field on Contact records, demonstrating the utility of Invocable Methods in encapsulating and reusing business logic within Salesforce.
Frequently Asked Questions:
Can you explain what Invocable Methods are in Salesforce and how they differ from standard Apex methods?
Invocable Methods in Salesforce are a specific type of method that you can define in Apex classes to make them accessible from Salesforce’s declarative automation tools, like Flow, Process Builder, or even external applications through API calls. The key distinction between Invocable Methods and standard Apex methods lies in their annotation and accessibility.
A standard Apex method is just a regular method within an Apex class that you can call from other Apex classes or triggers. These methods are great for encapsulating logic that you intend to reuse within your Apex codebase. However, they’re not directly accessible from Salesforce’s declarative tools.
Read more: Classes in Salesforce Apex
On the other hand, when you annotate a method with @InvocableMethod, you’re specifically marking that method as accessible from outside the Apex class through Salesforce’s declarative tools, like Process Builder and Flow. This annotation opens up a wide range of automation possibilities, allowing administrators and developers to invoke complex Apex logic without writing any code.
An Invocable Method must be static, can only have one input parameter, and this parameter must be a list, which allows the method to process multiple records at once, supporting bulk operations. The return type also needs to be a list. This design ensures that Invocable Methods are bulk-safe, aligning with Salesforce’s best practices for handling large sets of data efficiently.
So, the main difference is about accessibility and the context in which these methods are used. Standard Apex methods are for code-based scenarios within the Apex environment, while Invocable Methods bridge the gap between declarative automation tools and Apex, allowing for a more powerful and flexible automation framework within Salesforce.
How do you handle bulk data processing within Invocable Methods to ensure they are bulk-safe?
Handling bulk data processing within Invocable Methods is crucial for maintaining performance and avoiding governor limits in Salesforce. When designing Invocable Methods, it’s essential to ensure they are bulk-safe. This means the method can efficiently process large volumes
of records without hitting Salesforce governor limits, which are set to ensure that shared resources are used efficiently in the multi-tenant environment Salesforce operates in.
Read more: Methods in Salesforce Apex
To make Invocable Methods bulk-safe, I follow a few key practices:
- Use Collections Wisely: When processing records, I always use collections, such as lists or maps, to handle data. This approach allows for efficient querying and manipulation of large data sets. For example, rather than updating records one at a time within a loop, I gather all the records that need updating into a list and perform a single DML operation outside the loop.
- Efficient Querying: I make sure to structure SOQL queries to avoid querying inside loops, which can quickly lead to hitting governor limits with bulk data. Instead, I gather all necessary data identifiers first, then perform my queries outside of loops to retrieve all necessary data in as few queries as possible.
- Limit DML Operations: Similar to SOQL queries, DML operations (like insert, update, delete) are batched as much as possible to avoid executing these operations inside loops. By aggregating records into lists and performing DML operations on these lists, I minimize the number of DML statements and efficiently use the DML statements limit.
- Error Handling: Proper error handling is essential, especially when dealing with bulk operations. I use try-catch blocks to handle exceptions and utilize Database methods (like
Database.update(records, false)) to allow for partial success, where some records can fail to update or insert without causing the entire operation to fail. This approach is crucial for processing large batches of records, where individual record issues shouldn’t halt the processing of the entire batch. - Testing for Bulk: In my unit tests, I always include tests that simulate bulk operations, ensuring that my Invocable Methods can handle the maximum batch size that they might encounter in real-world scenarios. This helps to identify and address any bulk processing issues during the development phase, before they become a problem in production.
By adhering to these practices, I ensure that my Invocable Methods are robust, efficient, and capable of handling large volumes of data without exceeding Salesforce’s governor limits, maintaining optimal performance and scalability.
Describe a scenario where you used an Invocable Method in a Salesforce project. What was the problem, and how did the Invocable Method solve it?
Here is an example from my experience where using an Invocable Method significantly improved a business process in Salesforce.
In one of the projects I worked on, the client needed to automate the process of updating contact records based on interactions logged in a custom object called Interaction__c. The requirement was to mark a contact as “Engaged” in a custom field Engagement_Status__c on the Contact object if there had been any interaction with that contact in the last 30 days. The challenge was to implement this in a way that could be easily triggered by non-developers from a Flow, without writing complex Apex triggers or batch jobs that would require code deployment for any future adjustments.
Read more: Objects in Salesforce apex
To solve this, I developed an Invocable Method. This method would take a list of Contact IDs as input, query the Interaction__c object for any interactions related to these contacts within the last 30 days, and update the Engagement_Status__c field on those Contact records accordingly.
Here’s a simplified version of how I approached it:
public class UpdateContactEngagementStatus {
@InvocableMethod(label='Update Engagement Status' description='Updates the engagement status of contacts based on recent interactions')
public static void updateEngagementStatus(List<Id> contactIds) {
// Find interactions in the last 30 days for the provided contacts
List<Interaction__c> recentInteractions = [
SELECT Id, Contact__c FROM Interaction__c
WHERE Contact__c IN :contactIds
AND Interaction_Date__c = LAST_N_DAYS:30
];
Set<Id> engagedContactIds = new Set<Id>();
for (Interaction__c interaction : recentInteractions) {
engagedContactIds.add(interaction.Contact__c);
}
// Update contacts' engagement status if they have recent interactions
if (!engagedContactIds.isEmpty()) {
List<Contact> contactsToUpdate = [
SELECT Id, Engagement_Status__c FROM Contact WHERE Id IN :engagedContactIds
];
for (Contact contact : contactsToUpdate) {
contact.Engagement_Status__c = 'Engaged';
}
update contactsToUpdate;
}
}
}
This Invocable Method was then called from a Flow, which was triggered whenever an Interaction__c record was created or updated. This approach allowed us to dynamically update contact engagement status based on real-time interactions, without requiring manual intervention or complex coding solutions.
Read more: Variables in Salesforce Apex
The key to success in this scenario was the Invocable Method’s ability to encapsulate the logic in a way that was easily accessible to the Flow. It allowed for greater flexibility in the automation process and made it possible to adjust the logic in the future without needing to modify the Flow itself. This solution not only met the client’s needs but also provided a scalable and maintainable approach to managing contact engagement statuses.
This experience highlighted the power of Invocable Methods in bridging the gap between complex Apex logic and Salesforce’s declarative automation tools, enabling us to deliver a highly effective solution to the client’s challenge.
Checkout: Interfaces – Salesforce Apex

