Call an Apex method from Process Builder

green coconut trees near body of water
Reading Time: 3 minutes

Intro

As a thumb of rule in Salesforce you should always try to create new business logic through point-and-click but sometimes our logic it’s a bit special and we need some Apex code. This doesn’t mean you should concentrate all your flow , validations and rules in Apex, It means you should only implement the minimum and leverage the easy part to Process Builder itself, validation rule or any other

The Apex class

      
public with sharing class MyApexClass {
    
    @InvocableMethod(label='My Apex method'
                     description='A method to do something awesome'
                     category='Account')
    public static void run(List<id> ids){
        List<account> records = [SELECT Id, Name FROM Account where Id IN :ids];
        // Do something with the accounts...
        System.debug('Records to be processed: '+records.size());
    }
}
      </account></id>
    

To share or not to share

Use with sharing or without sharing keywords depending on your requirements

“Use the with sharing or without sharing keywords on a class to specify whether sharing rules must be enforced. Use the inherited sharing keyword on a class to run the class in the sharing mode of the class that called it.”

See more at Using the with sharing, without sharing, and inherited sharing Keywords

Create a Flow with Process Builder

Go to Setup -> Process Builder and create a new one like this:

Click on save.

Once created, click on add object, Select Account from the dropdown.

From the “Start the process” select “when a record is created or edited”

Click on Save and It will look like this:

Click on Add Criteria

Give a name for your criteria and select “No criteria, just execute the actions!”

Click on save and It will look like this:

Click Add Action

Select Action Type: Apex. Give an action name, in our case “run”

From “Set Apex Variables” click on “Add row”

Select “Ids”

Type: Field reference

And from “Value” select the Account ID

Select Account ID

Click on save and It will look like this:

Activate the flow and test it

The most important step: activate the flow by clicking on Activate button. Now go to any account and make a modification to execute your brand new Flow. If you have the developer console open you will see a log line.

,

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.


Related posts


Leave a Reply

%d bloggers like this: