How to Call Apex Class From Salesforce Flow : Bijay Kumar

How to Call Apex Class From Salesforce Flow
by: Bijay Kumar
blow post content copied from  SalesForce FAQs
click here to view original post



### Summary of the Content This tutorial explains how to automate processes in Salesforce by calling an Apex class from a Salesforce flow, especially when complex logic is required that cannot be handled by the flow alone. **Key Details:** 1. **Apex Class and Invocable Method**: To call Apex code from a flow, you need to create an Invocable method in the Apex class, which is marked with the `@InvocableMethod` annotation. This method must be public or global, static, and can only exist once per class. 2. **Creating the Apex Class**: The tutorial provides an example where an Apex class updates an account's site field based on the website value from a newly created opportunity. 3. **Flow Configuration**: The tutorial outlines the steps to create a screen flow that collects user input, creates an opportunity record, and then calls the Apex class to update the account's site field. 4. **Final Steps**: After creating the flow, it explains how to add it to the account record page and demonstrates the expected output after the flow is executed. ### Additional Context Salesforce flows are powerful tools for automating business processes, but they can sometimes fall short when it comes to implementing complex logic. By integrating Apex classes, users can extend the capabilities of flows, allowing for more sophisticated automation. This tutorial is particularly useful for Salesforce developers and administrators looking to enhance their automation strategies. ### Hashtags for SEO #Salesforce #Apex #SalesforceFlow #Automation #InvocableMethod #SalesforceTutorial #CRM #SalesforceDevelopment #SalesforceAdmin #CloudComputing #BusinessAutomation


Sometimes, to automate the process by using the Salesforce flow, the capabilities are limited for complex logic. So, for that, we can use an apex class to automate the process and then call an apex class from a flow.

In this Salesforce tutorial, we will learn how to call apex class from Salesforce flow. In this, I will explain what is an invocable method; then, we will create an apex class and then call that apex class by the flow.

What is the Invocable Method in Salesforce?

To call Apex code from a flow, we need to create an Invocable method within the Apex class. This method is annotated with @InvocableMethod, which makes it accessible to the flow.

The label attribute in the annotation specifies the display name of the Apex Action. Each class can contain only one Invocable Method and accept a single parameter.

Now, there are some considerations when declaring the invocable method in the apex class.

  • Class Visibility: The Apex class must be defined as public or global. So that it can be accessible from the flows.
  • Method Visibility: The Invocable method must be static and public or global.
  • Class Type: The class must be an outer class.
  • Invocable Method Limit: There can be only one Invocable method per class.

Example: Call Apex Class From Salesforce Flow

In the following step, I will explain how to call the apex class in Salesforce flows. For that, first, we need to create an apex class with the invocable method.

Create Apex Class WIth @InvocableMethod

Now, we will create a class where we can implement the complex logic that will not be able to be implemented by flow. After creating the class, we will call the apex class from Salesforce flow.

Let’s take a scenario: When an opportunity is created from the account record page, the account’s site field in the account details will be updated with the website value entered in the opportunity object.

Here, we created an apex class with @invocableMethod so that we can access this class in the flow.

public class CallApexByFlow {
    
    @InvocableMethod
    public static List<String> updateAccountSite(List<Id> ids) {
        List<Opportunity> oppList = [SELECT AccountId, Website__c FROM Opportunity WHERE Id IN :ids];

        Set<Id> accountIds = new Set<Id>();
        for (Opportunity opp : oppList) {
            if (opp.AccountId != null) {
                accountIds.add(opp.AccountId);
            }
        }

        Map<Id, Account> accountMap = new Map<Id, Account>(
            [SELECT Id, Site FROM Account WHERE Id IN :accountIds]
        );

        List<String> accountSites = new List<String>();
        List<Account> accountsToUpdate = new List<Account>();

        for (Opportunity opp : oppList) {
            if (accountMap.containsKey(opp.AccountId)) {
                Account acc = accountMap.get(opp.AccountId);

                if (String.isEmpty(acc.Site)) {
                    acc.Site = opp.Website__c;
                } else {
                    acc.Site += ', ' + opp.Website__c;
                }

                accountSites.add(acc.Site);
                accountsToUpdate.add(acc);
            }
        }

        if (!accountsToUpdate.isEmpty()) {
            update accountsToUpdate;
        }

        return accountSites;
    }
}

Configure Class in the Flow

In the below steps, I will explain how to create flow and call apex class to automate the process.

1. Create Screen Flow

Go to Setup -> Flows -> New Flow -> Start From Scratch -> Screen Flow.

Add the Screen Element into the flow builder by clicking on (+) Add Element and configure the screen properties by using the API name and label.

Drag the following input from the component section into the screen canvas:

Components Lable
Text Opportunity Name
Date Close Date
Picklist Stage Name
Text Website
Screen Flow in Salesforce

2. Create Variables in Flow

  • recordId: This variable is used to store the Account Record ID. When the flow is triggered from an account record page(for example, when a user creates the opportunity record), the current account’s ID is passed into this variable.
Create Variable in Salesforce Flow
  • OpportunityId: This variable is used to store the opportunity ID after the opportunity record is created within the flow. It is initially empty and will be populated with the ID of the newly created opportunity once the flow executes the “Create Record” action.
Store ID in Salesforce Flow

3. Create Opportunity Record

Add the ‘Create Record’ element onto the canvas and provide the Label and API name. Select “Opportunity” as the object to create. Set the field values for the opportunity.

Field(Opportunity) Value(Screen Component)
AccountId {!recordId} (created Variable)
CloseDate {!Close_Date}
StageName {!StageName}
Name {!Opportunity_Name}
Website {!Opportunity_Website}
Create Record Element in Salesforce Flow

We also need to store the created opportunity ID into a variable that we created for that. Check the box for ‘Manually assign variables‘. Provide a Variable to store OpportunityId and click Done.

Manually Assign Variable in Salesforce

4. Add Action Element

Now, after creating the opportunity record, we need to call the apex class, where we implemented logic for updating the account site.

  • Add an Action element onto the canvas.
  • In the Search box, search for the Call Apex By Flow.
Call Apex By Flow Action in Salesforce
  • Provide a Label and API Name for the action.
  • In the Set Input Values for the Selected Action, add the OpportunityId variable where we have newly created opportunity ID– {!OpportunityId}.

Then click the Show Advanced Options dropdown.

How to Call Apex From Salesforce Flow

Now, first, we need to create a variable to store the values that we will be getting from the action, which is the apex class. Here, I created a Text variable named ActionValue.

Salesforce Flow to Call Apex Class

Now check the checkbox Manually assign variables from the advanced option. Then, in the Store Output Values, select the created text variable(ActionValue).

Create Salesforce Flow to Call Apex Class

Now, after executing the action element, the link will get into the created variable, and that link will be displayed in the screen element using the Display Text component. So here I added text and the variable in which we have output value.

After that, click the Done button and Save the flow.

Screen Element in Salesforce Flow

For this flow, I provided the ‘Call Apex From Salesforce Flow‘ name and saved the flow. After that, I Activated the flow, and only then can we add screen flow to the record page.

Call Apex Class From Salesforce Flow

5. Add Screen Flow to Account Record Page

Now, we need to add the created screen flow to the account record page. For that, navigate to the Account object tab and open any record. Click the Gare icon -> Edit Page -> the Account Record Page will open.

To add the flow, in the Component, search for Flow, drag and drop where you want on the record page. In the flow, select the flow label that you provided.

Then, in the OpportunityId field, check the pass record ID into the variable, and the field will automatically take the ID, and the same is true for the recordId variable.

Finally, Save the changes and activate the record page.

Add Screen Flow to Record Page

Output

In the below image, you can see I have opened an account record in which the Account Site field is blank.

Update Record Using Salesforce Flow

Also, that account only has two related opportunities. Now, I have provided value to the screen flow that we added on the account record page to create an opportunity record. After providing value, click the Next button.

Create Opportunity Record Using Screen Flow

As you click the next button, the opportunity record will get created, and the Action element will also call the Apex class, where we implemented logic to assign website field value (opportunity) to the Account Site file(account).

Here, you can see, using the display text component, we displayed the Account Website Link, which was provided in the opportunity creation.

Apex Class To create Record in Salesforce

Also, the opportunity that we created is related to the account object.

Create Related Record Using Salesforce Flow

As you open the account details, you will see the Account Site, the same as we provided on the opportunity website.

Update Record Using Flow

In this way, we can call the apex class from Salesforce flows. So, in the apex class, we can implement complex logic that we can’t create using flow, and then using the flow, we can call the Apex class.

Conclusion

I hope you have got an idea how to call apex class from Salesforce flow. In that, I have explained, what an invocable method is; then, we created an apex class where we implemented logic to update the accounting field and then called that apex class by using flow.

You may like to read:

The post How to Call Apex Class From Salesforce Flow appeared first on SalesForce FAQs.


February 13, 2025 at 01:30PM
Click here for more details...

=============================
The original post is available in SalesForce FAQs by Bijay Kumar
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce