Salesforce Invocable Apex Methods: A Complete Guide

January 16, 2025
148 Views
Salesforce Invocable Apex Methods: A Complete Guide

Salesforce professionals often encounter scenarios where declarative tools like Flows or Process Builder require additional functionality beyond their native capabilities. This is where Invocable Apex Methods step in, providing a powerful bridge between declarative automation and custom logic.

In this blog, we’ll dive deep into Invocable Apex, complete with code examples and practical use cases to help you leverage this feature effectively.

What Are Invocable Apex Methods?

Invocable Apex methods are static Apex methods annotated with @InvocableMethod, making them accessible to declarative tools like Flows and Processes. They are ideal for implementing reusable, scalable, and complex business logic without compromising on simplicity for admins.

  1. Invocable method must be static and public or global with @InvocableMethod annotation, and its class must be an outer class.
  2. Supports batch processing, making it capable of handling multiple records in a single invocation.
  3. Input/Output parameters can be a list of a primitive data type or a list of lists of a primitive data type
  4. They are subject to the same governor limits as standard Apex code, including limitations on SOQL queries and DML operations
Also Read

Don’t forget to checkout: Salesforce Service Cloud Tips and Best Practices.

Anatomy of an Invocable Apex Method

Below is a simple example of an Invocable Apex method:


public class UpdateAccountIndustry {
    @InvocableMethod(
        label='Update Account Industry'
        description='Updates the Industry field for a list of Accounts.'
    )
    public static void updateIndustry(List accounts) {
        for (Account acc : accounts) {
            acc.Industry = 'Technology';
        }
        update accounts;
    }
}
        

 

Use Cases for Invocable Apex Methods

1. Custom Record Updates

Scenario: Your Flow needs to update a specific field based on complex criteria that can’t be configured declaratively.

Example: The method above can be used to update the Industry field for Accounts processed in a Flow.

2. External System Integration

Scenario: Sending data to or retrieving data from an external API.


public class CallExternalAPI {
    @InvocableMethod(
        label='Send Data to API',
        description='Sends a list of contact details to an external system.',
        callout=true
    )
    public static void sendData(List contacts) {
        for (Contact contact : contacts) {
            // Pseudo-code for making an HTTP callout
            HttpRequest req = new HttpRequest();
            req.setEndpoint('https://api.example.com');
            req.setMethod('POST');
            req.setBody(JSON.serialize(contact));

            HttpResponse res = new Http().send(req);
            if (res.getStatusCode() != 200) {
                System.debug('Error: ' + res.getBody());
            }
        }
    }
}
        
 3. Data Transformation

Scenario: A Flow needs to modify data before saving it.

Example: Standardize phone numbers for contacts by formatting them in a consistent pattern (e.g., (123) 456-7890).


public class StandardizeContactPhones {
    @InvocableMethod(
        label='Standardize Contact Phone Numbers' 
        description='Formats phone numbers for a list of Contacts to a standardized pattern.'
    )
    public static void formatPhoneNumbers(List contacts) {
        for (Contact contact : contacts) {
            if (contact.Phone != null) {
                String cleaned = contact.Phone.replaceAll('[^0-9]', '');
                if (cleaned.length() == 10) {
                    contact.Phone = '(' + cleaned.substring(0, 3) + ') ' + cleaned.substring(3, 6) + '-' + cleaned.substring(6);
                } else {
                    System.debug('Invalid phone number for Contact: ' + contact.Id);
                }
            }
        }
        update contacts;
    }
}
        

 

Best Practices for Invocable Apex Methods

  1. Focus on one specific task per method to ensure clarity and maintainability.
  2. Write your code to handle lists of records, even if the initial use case involves single-record processing. This ensures scalability.
  3. Use meaningful labels and descriptions for admin-friendly implementation.
  4. Use try-catch blocks and debug logs to manage and log errors effectively, also write unit test cases covering invocable apex methods.

Limitations of Invocable Apex Methods

  1. Simple Input and Output Types: Only certain data types are supported, such as primitives, sObjects, or lists.
  2. No Chaining: Invocable methods cannot call each other directly.

Resources for Further Learning

Conclusion

Invocable Apex Methods — an Advanced tool for Salesforce Professionals (automation and customization at once with simplicity for admins) These are designed primarily to provide developers a way of packing complex business logic in a library that can be re-used most effectively through invocable methods. When used in best practices, these methods allow to create production classes which scale and provide modern solution to bridge imperative to declarative abstractions.

Start experimenting with Invocable Apex today and unlock new possibilities for your Salesforce org!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Our Contributor

Varsha Dhage

7X Certified Salesforce CPQ consultant & Advanced developer | CPQ Helping companies generate Lead-to-Cash | SFUG Speaker

Get the latest tips, news, updates, advice, inspiration, and more….

Contributor of the month
contributor
Ila Anmol Verma

Salesforce Tech Lead | 12X Salesforce Certified | Technical Writer

Categories
...
Boost Your Brand's Visibility

Want to promote your products/services in front of more customers?

...

Leave a Reply

Your email address will not be published. Required fields are marked *

0%
Think you know Salesforce?
Fill in the details to Get Started

What is true about dynamic dashboards?

A Salesforce Administrator has 7 million records that need to be loaded into Salesforce and wants to do it in one batch. How can the records be uploaded in one batch?

Which of the following can a Case Queue be used for?

Which of the following statements are true about resetting passwords when users get locked out of a Salesforce org that does NOT have single sign-on enabled through an identity service other than Salesforce?

If a user is working in Salesforce when the login hours end, what will happen?

Your score is

0%

This will close in 0 seconds