Call Apex Invocable Method From Salesforce Flow – Part 2

Call Apex Invocable Method From Salesforce Flow – Part 2

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

In Salesforce, bulkification of code is essential due to the platform's multi-tenant architecture and the associated governor limits. Salesforce operates on a multi-tenant architecture, meaning that multiple customers (organizations) share the same underlying hardware and infrastructure. This shared environment necessitates strict resource management to ensure that no single customer monopolizes resources and impacts the performance of others. To enforce fair resource usage, Salesforce imposes governor limits on Apex code, which is the platform's programming language. 

Without bulkification, Apex code would process records one at a time. This becomes inefficient and can easily lead to exceeding governor limits when dealing with large datasets. Bulkification is the practice of writing Apex code to handle multiple records in a single transaction, minimizing the number of SOQL queries and DML statements. 

I have already published a blog post/video covering the basic use case of handling a single record type. If you haven't checked it out, I will highly suggest you first go through that first as it creates the foundation. I will provide the link below. But in this post/video, I will share a more complex use case where I will create my own input type and pass that to the Apex method. In return, the Apex method will return me a custom output type.

The form you have selected does not exist.

Watch The Video Or Read The Article (Or Do Both smile)

Let's Understand The UseCase

The Use Case I will be implementing today is - "From Screen Flow, I will be passing a list of cases and a list of contacts to the Apex method. The Apex method will return the flow two lists. The first list will contain the case description of all selected cases. The second list will contain the contact names of all selected contacts".

This is a complex use case. I will be creating my own custom input and output types to implement the above scenario.

Implementation Approach

To implement the above use case, I will be writing an invocable apex class which I will call from record-trigerred Salesforce Flow. Again very straightforward. So without any further delay, let's start implementing the use case.

Let's Write The Apex Class

As you can see in the below Apex class, I have created custom InputVariable and OutputVariable. Both of them are inner classes. InputVariable contains Case List and Contact List. Both of them are annotated with @InvocableVariable. The reason for this annotation is that from Salesforce, I will be passing selected cases and selected contacts to the invocable apex method. The input parameter for the apex invocable method will be a list of InputVariables. The invocable apex method will return a list of OutputVariables, which contains two lists. One will contain case's description, whereas the other will contain the selected contact's name.

And finally the InvocableMethod fetchCaseAndContactDetails dealing with my custom InputVariables and OutputVariables.

public with sharing class FetchCaseContactInformation { 
 @InvocableMethod(label='Fetch Case And Contact Details' description='Returns the list of strings holding Case Descriptions and Contact Names' )
 public static List<OutputVariables> fetchCaseAndContactDetails(List<InputVariables> inputs) {
 System.Debug('--++-- SD: Inside fetchCaseAndAccountDetails'); 
 List<OutputVariables> outputs = new List<OutputVariables>();
 OutputVariables output = new OutputVariables();
 List<String> allCaseDescriptions = new List<String>();
 List<String> allContacts = new List<String>();  for(Case singleCase : inputs.get(0).allCases){
 allCaseDescriptions.add(singleCase.description);
 }
 for(Contact singleContact : inputs.get(0).allContacts){
 allContacts.add(singleContact.Name);
 }
 output.allCaseDescriptions = allCaseDescriptions;
 output.allContactNames = allContacts;
 outputs.add(output);
 return outputs;
 }  public class InputVariables {
 @InvocableVariable
 public List<Case> allCases;
 @InvocableVariable
 public List<Contact> allContacts;
 }
 public class OutputVariables {
 @InvocableVariable
 public List<String> allCaseDescriptions;
 @InvocableVariable
 public List<String> allContactNames;
 }
}

Let's Build The Flow

This is going to be a screen flow. The first two elements of the flow are to fetch cases and accounts from the organization with the Get Records element.

With that in the next screen element, I will be displaying fetched cases and accounts inside a datatable as shown below in the screenshot.

In the next step, I will be passing the selected cases and contacts to my invocable method. The configuration is displayed below in the screenshot.

As you can see in the above screenshot, I am passing Selected Cases and Selected Contacts into the allCases and allContacts input variables. Both of these variables are annotated with the InvocableVariable annotation.

Now in the next screen, I am displaying the return values (from the Apex invocable method) inside a new screen with a Display Text element. Configuration is shown below.

Reference Documents

Final Thoughts

I hope this two-part series of blog posts and YouTube videos will provide you with all the details that you need to work with Invocable Methods and call them from Salesforce Flow.

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

Comments

Call Apex Invocable Method From Salesforce Flow – Part 1

Call Apex Invocable Method From Salesforce Flow – Part 1

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

In Salesforce, bulkification of code is essential due to the platform's multi-tenant architecture and the associated governor limits. Salesforce operates on a multi-tenant architecture, meaning that multiple customers (organizations) share the same underlying hardware and infrastructure. This shared environment necessitates strict resource management to ensure that no single customer monopolizes resources and impacts the performance of others. To enforce fair resource usage, Salesforce imposes governor limits on Apex code, which is the platform's programming language. 

Without bulkification, Apex code would process records one at a time. This becomes inefficient and can easily lead to exceeding governor limits when dealing with large datasets. Bulkification is the practice of writing Apex code to handle multiple records in a single transaction, minimizing the number of SOQL queries and DML statements. 

In this blog post, I will share the process to bulkify your invocable apex method call from Salesforce Flow.

The form you have selected does not exist.

Watch The Video Or Read The Article (Or Do Both smile)

Let's Understand The UseCase

The Use Case I will be implementing today is - "Any time a Case is created or updated with fetchContactName field (Custom Field of type Checkbox) checked, Contact's Full Name from that case should be returned".

This is a very simple use case. I don't want to make the use case too complex, as my intention is to demonstrate the way to bulkify your apex invocable callout implementation so that you can avoid some unnecessary issues.

Implementation Approach

To implement the above use case, I will be writing an invocable apex class which I will call from record-trigerred Salesforce Flow. Again very straightforward. So without any further delay, let's start implementing the use case.

Let's Write The Apex Class

As you can see in the below Apex class, I will be passing the list of ids (which is basically the case ids passed from the flow). This is important. I am dealing with a list of ids and not a single id. This is the first step to make things bulkified. Rest of the code is very straightforward. Using the ids, fetching the case's contact names, and then storing them in the list. The same list is being returned at the end of the code execution.

public with sharing class FetchContactDetailsFromCase {
 @InvocableMethod(label='Fetch Contact Names' description='Returns the list of strings holding contact names' category='Case')
 public static List<String> fetchContactNames(List<ID> ids) {
 System.Debug('--++-- Inside fetchContactNames --++--');
 System.Debug('--++-- List of Case Ids : ' + ids);
 List<String> allNames = new List<String>();
 //Fetch Case Details
 List<Case> allCases = [Select Id, Contact.Name From Case Where Id in: ids];
 for(Case singleCase : allCases){
 allNames.add(singleCase.Contact.Name);
 }
 System.Debug('--++-- Contact Names : ' + allNames);
 return allNames; 
 }
}

Let's Build The Flow

This is going to be record-triggered flow and from the flow, I will be calling the invocable apex. Screenshots given below.

An important thing to notice is from the second screenshot above. While passing the record id to the Apex Invocable method, I am passing the triggering record ID (a flow variable). But if you can remember, the apex class is expecting the list of ids. This is where the Salesforce magic starts. Salesforce Flow will make sure if there are multiple records being updated satisfying the condition of this flow, instead of calling the flow that many times, Salesforce will club them in one transaction (max 200 records) and pass the list of record ids. This is how the bulkification being handled in Salesforce Flow.

Execute And Check The Debug Log

Now is the time to execute some code and check the behavior. For that I will be executing the below code snippet from Developer Console's Execute Anonymous Window. 

List<Case> allCases = [Select Id, fetchContactName__c From Case Limit 5];
for (Case singleCase : allCases){
 singleCase.fetchContactName__c = true;
}
update allCases;

The above code snippet will update 5 cases with the fetchContactName checkbox checked. This will initiate the record-triggered flow, and finally all those 5 case record ids will be passed into the apex invocable class. From the debug log, it is very clear that Salesforce passed all 5 ids in one single transaction. (screenshot below).

But the surprise element is still pending. Salesforce will also make sure that it will put the contact names in the same sequence that case ids came as input. Which is super helpful to do any work inside Flow after the invocable call. You as a developer don't need to do any extra logic and you can reply on the output from the invocable apex to perform your business logic.

Reference Documents

Final Thoughts

I hope this blog post and video will give you the clarity to write your next flow and invocable apex class in the correct way following the best practices. 

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

Comments

How To Use Startup Scripts While Creating Virtual Machines in Google Cloud Platform

How To Use Startup Scripts While Creating Virtual Machines in Google Cloud Platform

Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

In Google Cloud Platform (GCP), a startup script is a script that runs automatically when a virtual machine (VM) instance starts up. It's a powerful tool for automating tasks like:

  • Software Installation: Install necessary software, packages, or dependencies.
  • System Configuration: Configure system settings, environment variables, and services.
  • Service Startup: Start required services or applications.
  • Updates and Patches: Apply system updates and security patches.

Watch The Video Or Read The Article (Or Do Both smile)

The form you have selected does not exist.

What Are The Benefits?

There are multiple benefits, like:

  • Time-saving: Automates repetitive tasks.
  • Consistency: Ensures consistent VM configurations.
  • Scalability: Easily deploy and manage multiple VMs with the same configuration.

Ways To Use Startup Scripts

There are literally two ways you can use the Startup Scripts while creating Virtual Machines on the GCP platform

  • Write the Startup Scripts specific for that Virtual Machine
  • Write startup scripts, store them in Google Cloud Storage Bucket, and refer to them while creating Virtual Machine.

In this blog post, I will explain both ways.

# 1: Create Startup Scripts For Virtual Machine

In this approach, I will create the Startup Script for the Virtual Machine and add that while configuring it. 

While doing the configuration of the Virtual Machine, I will click on Advanced and then under Automation section, I will include my Startup Script (mentioned below).

#!/bin/bash
echo "*** Startup Script From Automation Section ***"
apt-get update
apt-get install -y apache2
echo "<h1>Hello World from technical potpourri !!</h1>" > /var/www/html/index.html

Now to check whether the Startup Script has executed successfully or not, I will check the log. To do that, I will go inside the virtual machine by clicking on the name from the console. Once there, I will click on the "Serial port 1 (console)" link to open the logs in a different tab. This is the place where I can find out the entire log and search to make sure my startup script has executed successfully.

Finally, when I open the external IP in a different tab, I will see that new content in the window, which indicates that my startup script has executed successfully.

So that's awesome. But if you think deeply, this way is good for one or a few virtual machines where I can add the startup scripts for each of the virtual machines while doing the configuration for them. But now if you think from a bigger team's standpoint, where multiple developers are working on creating multiple virtual machines, this approach is not efficient. Because it can introduce errors, developers can change the startup script. Instead we should have one startup script which can be shared by all the virtual machines.

And that is what the second approach is all about.

# 2: Share Startup Scripts For All Virtual Machines

In this approach, I will first create and save the startup script in my local desktop with a name "startup.sh" (You can use any name). 

After that I will create the Google Cloud Storage Bucket and upload the startup.sh file inside the bucket. Screenshot given below.

Once the startup script is inside the bucket, I will refer to it while configuring the virtual machine. Inside virtual machine configuration section, under Metadata, I will add the key value to refer to the startup script

Key: startup-script-url

Value: gs://my-startup-script-bucket/startup.sh

Once the virtual machine is ready, I will see the details while opening up the External IP in a new tab.

So now you can understand that with this approach, all of your team members can use the same startup script while creating new virtual machines. This is definitely the preferred approach.

Access Metadata Using Startup Scripts

Using Startup Script, it is possible to access the metadata that is being configured in Virtual Machine. For that this is going to be my startup script where I am fetching the metadata data with key name as Foo and displaying them inside index.html file.

#!/bin/bash
METADATA_VALUE=$(curl http://metadata.google.internal/computeMetadata/v1/instance/attributes/foo -H "Metadata-Flavor: Google")
echo "*** Startup Script From Automation Section ***"
apt-get update
apt-get install -y apache2
cat <<EOF > /var/www/html/index.html
<h1>Hello World from technical potpourri !!</h1>
<html><body><p>Accessing metadata value of foo: $METADATA_VALUE</p></body></html>
EOF

Once the starup script is ready, I will upload them inside the same bucket with a different name let's say - new-startup.sh. With the file available inside bucket, I will configure the virtual machine. Everything will be same, just two differences as shown in the screenshot below

With this configuration, when I will open the external IP in a separate tab, I will see the below details where the metadata is being fetched in Starup Scripts and then dipslayed.

Final Thoughts

That's all you need to know about startup scripts in Google Cloud Platform and it's usage. Please provide me your comments on how you use this in your project today. Thanks !!

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

Comments