How to Build a Flow Action with Apex

The other day I built a flow action that generates random numbers. While doing it, I recorded the process, because we don’t have a lot of tutorial material on how you can turn a chunk of useful Apex code into a nice, declarative flow action.

Here it is.

For a general introduction to the invocable action interface, check this out.

Understanding Invocable Actions

Easy Random Numbers Come To Flow

So I was reading this thread that mentioned random numbers, and then I read this great post about building a Blackjack game out of flow, and the Monty Python-caliber dry humor (which may or may not be intentional; I haven’t figured that out yet) about the complicated math necessary to generate pseudo-randomness. And then I thought about how easy it is over in Apex-land to generate random numbers, so I built a Flow Action you can install into your org that takes two values and generates a true random number in that range.

Check it out here.

Guest Post: Duke and Luke’s Blackjack-in-Flow

While browsing reports of flow sessions at Dreamforce, I came across two guys claiming to implement an Entire Heckin’ Blackjack inside of Flow. This is My Kind of Dreamforce Session, but I wasn’t able to make it because they keep Product Managers very busy at Dreamforce. As of this moment I’m still waiting for the video to get posted, but in the meantime I asked them to write a blog post. As you can see, this flow involves everything: Steps, Debugger, Lightning Component, Formulas. It’s really impressive, and the blog post is presented here.


Architect: Sean Dukes
Coder: Luke Kozakewycz

By Sean Duke

It all started at a Salesforce user group. I was doing a presentation on Lightning Flow. I’d used a ‘Hello World’ Lightning component and showed how you could change the greeting based on the region of the person. It went down pretty well, but it was hardly the rich user experience you read about.

Fast forward a few weeks and for some reason I had the idea that Blackjack would be a great visual use case. I sketched out a basic design and it seemed like it ought to work, so I submitted the idea as a Dreamforce talk. I didn’t expect things to go any further, so it was something of a surprise when a few weeks later, the email came through. “Your idea has been accepted, can you run us through your slides next week?”

“Yes, of course.” There followed an interesting few days where we put some slides together and tried to turn those early sketches into something that at least proved that what we wanted to do was possible.

“The first thought that struck me was that I’d never played Blackjack.”

The first thought that struck me was that I’d never played Blackjack. There could be experts in the room. I needed to truly understand how to play the game, so I wouldn’t get found out. I hunted around the internet and interviewed a couple of people who had played. My initial ideas weren’t far off, but, now that I had my user stories, it was interesting how much like a real project this was becoming.

In Blackjack, you typically have more than one deck of cards and they’re not shuffled between every hand. But they are shuffled. The first job was to get those cards and shuffle them. Salesforce doesn’t have a random number function, which would have made our life easy, so we had to come up with another way.

If you think about it, when you shuffle cards it isn’t random. The order they start in determines the order they end up in. We didn’t need random, we just needed unpredictable. So how do you do that?

There are in fact several ways you could do this. This is mine …

The solution we came up with was to use two objects. The first object was the base deck. This contained the 52 cards, with their value, an image url, the name and whether the card was an ace or not. We also assigned each card a different five-digit prime number.

For the first shuffle, we looped through the base deck and added two of each card to a new sObject Collection. As we did that, we calculated a number we call the seed.

The formula was pretty simple.

The formula was pretty simple. Multiply one thousand plus the time the user was created in hundredths of a second by the card prime number and then by a second five-digit prime number. This gives you a number of between twelve and fourteen digits. We then take the right hand seven digits which is our first unpredictable number.

VALUE(RIGHT(TEXT([Card prime number]*([Time Created]+1000)*[Prime number 1]),7))

When we add the second card, we use a different prime number. We now have 104 cards in an sObject collection with 104 unpredictable seed numbers and we save this to a second object called Card Deck that has a lookup to the user. If we sort by this, then each card deck will have a different card order for each player unless they created their accounts at precisely the same second.

We don’t stop there.

We don’t stop there.We use a second field called the shuffle order. This is a formula field that multiplies the seed by a ten digit prime number and by the record number of the card in the card deck (a sequential number) and then we take the middle seven digits. This is the field we actually sort by. Even if two players started at exactly the same time, their shuffle orders would be radically different.

Shuffling again is simple. All we do is copy the shuffle order to the seed field and this creates a new shuffle order. It works really nicely.

It’s easy and satisfying to test this. The first thing to do is create a list view that shows the user’s cards.

Then you go to the shuffle flow — we have a separate flow because we re-use it in several places.

Now you click the debug button and enter in the user ID, which is the only input parameter required by the flow and click Run.

It’s worth noting that this debug method actually does run and changes data. It’s not something you want to be doing in your production org with an untested flow! For our purposes though, it’s great. Click refresh and you can see the result.

So shuffling was a good start and relatively straightforward. Now for the game itself. This was definitely the heavy thinking part. The breakthrough came when we started to look at the journey of each individual card.

We load the shuffled deck into an sObject Collection and then follow each card around. We use a series of variables to record what is happening with the player and the dealer and then we make decisions based on the value of those variables.

It took a while, but this is what we ended up with.

Break this down and the first part of the flow is all about getting ready. The right hand loop represents the playing of a single hand and the left hand loop runs when that hand is over and we get ready to play the next one. Simple 🙂 In all we ended up with 34 elements in the flow and four of those are to stop people cheating!

We should probably confess at this point that we decided splits, doubling and insurance were out of scope for our project. I have no doubt we could add those things in now.

A couple of things we noticed as we went along. Firstly, we were really diligent about creating descriptions on every flow element as a first step. Writing in long hand exactly what we expected to happen at each stage made completing each element much easier and the whole thing was easier to debug. The other thing that was interesting, was that the more efficient and the more correct our flow became, the fewer elements we had and the more elegant the flow itself appeared. I’m particularly proud of the fact that in the whole flow, we only ended up with one crossing connector and though I’ve tried, I can’t see a way to get rid of it. It will be interesting to see what this looks like when we put it in the new Flow Builder.

One thing that helped to keep the flow manageable was using formulas. For example, we have an assignment step where we work out the outcome of the game when the dealer has finished playing. We could have done this with a decision element and five assignments, but we were able to achieve the same thing with one assignment and a formula. Our assignment step sets the value of the GameOutcome variable to a formula result. This trick really cut down on complexity.

We tested our game as we were building it using a variation on that original ‘Hello World’ component. We had a view showing us the player’s card deck and then put our component onto a page, then we could compare the two side by side and make sure the game was behaving as we expected. This was crude and we didn’t have hit and stand buttons, but it was very useful.

At this point we had a working game and my coding skills had reached their limit. It was time to call in a professional! The Lightning component we built looks great, but it does remarkably little work. The screen element passes various values into the flow so that we know what we want to display. It has a timer, so you can see the cards being dealt out and it does look pretty, but that’s effectively it.

The only time the Lightning component changes a value is when the player hits stand. There’s an attribute called DealToPlayer. This will be true if it’s the player’s turn and if the player hits ‘Stand’ then this changes to false and is passed back to the flow. The flow does the rest.

Now all we needed to do was drag our flow onto the Lightning community home page (or in this case onto a Contact page for testing) and that was that.

We had our game and we could and did take it to Dreamforce. We even managed to get the whole audience playing in our special community and we had prizes, including for the fastest loser! Overall, it was great fun and a hugely interesting learning experience. If you want to find out more then, when the recording comes out, you should watch it.

Architect: Sean Dukes

Coder: Luke Kozakewycz

We both worked on bits of all of it.

© Sean Dukes 2018

The Horizontal Rule Flow Screen Component

Note: this is not an official Salesforce product and is not supported by Salesforce.

Built a simple component recently that provides flow screens with this simplest of html entities. The wrinkle is that it’s styleable, providing an effective, colorful section header.

Check out the video.

September Content Report — Flow and Components

In which we draw your attention to great things being written:

Delete Records Using Process Builder

Using the new Page Reference mechanic to pass query parameters from URLs into Lightning Components

A great tutorial on Flow Stages by Jennifer Lee

Another great tutorial by Jennifer Lee on Local Flow Actions

Arnab’s introductory blog post covering the new Flow Builder

Bob Buzzard on Background Utility Items

Doug Ayers Deep, Useful, and Interesting Material on Calling REST from a Lightning Component , specifically his new library.

Know about a good blog post covering Flow, Components and Salesforce AppDev? Let us know about it at

Salesforce Lightning Flow — Using Advanced SOQL

UPDATE: This post discusses how to make SOQL calls in Flow using apex code. However, there are also some installable components that let you create SOQL calls with point-and-click UI in flows. Learn more.

It’s surprisingly straightforward to add a complex SOQL query to your Lightning Flow.

The process involves creating a simple Apex class that carries out your query, and then ensuring that class shows up in Flow Builder as a declarative building block that can be dragged into your flow.

Invocable Actions is the key technology that enables you to publish your apex into flows .  Learn more about Invocable Actions.

Here’s an example of an apex class I wrote to carry out a single, complex SOQL query.

Note that in this pattern, I create a Requests class to store the inputs that my SOQL query will need and a Results class to define the values that my flow action will return to the flow.

In this particular example, I carry out my SOQL query in two parts. I first retrieve the name of the user and then retrieve a count of all cases associated with that user name.

I then create a Result instance and pack it with the important values returned with my queries:

Results curResult = new Results();
curResult.severeCaseCount = severeCaseCount;
curResult.revenueTier = curUser.RevenueTier__c;

Finally, I create a List container and add my Result to it. I use a List even though I know I’ll only have a single Result. That’s just part of how the Invocable Actions interface works: each action is expected to return a List (this makes it possible for the interface to support collections and single value responses with a single method).

Because I’ve annotated a method in my AssessCustomerStatus class with @invocableMethod, this functionality will now appear in flow as a declarative building block:

If you can create advanced SOQL queries, you‘re enough of salesforce dev to expose them as declarative flow actions. This opens a lot of new applications up to you.

New Flow Content

Flow Builder Posts

Check out Arnab Bose’s post on the new Flow Builder. Arnab heads up product management for Lightning Flow. The new Flow Builder is part of this Platform press release, as well.

New Flow Solutions Category on App Exchange

A new Flow Solutions section has been added to the AppExchange.

This includes a range of new flow actions, components and solutions.

The New Page Components Section

  1. Eric Smith, who has added great value with his Lookup component improvements, has posted a couple of cool Page Components. These are designed to go not in flow screens but in Lightning pages. We’ve created a new section here. The new components include:

Field Update Button

This is a generic Lightning Component that can be used in place of a JavaScript button to set the value of a single field in a record. This is handy for using a button to trigger a Process Builder.

Quick Action Button

This is a generic Lightning Component that allows a Button to execute a Quick Action. The Button can be placed anywhere on a Lightning Record Page.

See the New Official Screen Components online on Tuesday at Release Readiness Live

Stimulated by demand and response from these unofficial community components, Salesforce has finished adding a new batch of official screen components to the upcoming Winter ’19 release. I’ll be demonstrating them at the Release Readiness Live Platform broadcast on Tuesday 9/18:

Almost all of this batch derives in some way from the unofficial community work and feedback that has been received. For example, the official Dependent Picklist component will support field dependencies in no small part due to this comment from last February:

Many of the other components being created are variations of the uber input component introduced here, created by Ryan McConnell:

So we’re establishing a pipeline where the best community components get incorporated into the official Salesforce product, and there’s more to come.

Component-building Session at Dreamforce

I’ll be hosting a brief session with Rakesh “Automation Champion” Gupta focusing on using and creating components, including some glimpses of official components that didn’t quite make the Winter ’19 deadline and will be coming in Spring ’19:

…and here’s the overall schedule of Flow-related sessions at Dreamforce:

Building Expressions in Strategy Crafter

Expressions are used in several NBA elements to determine at run-time which propositions should be allowed to flow through.

You can build expressions one of two ways:

  1. Formula Mode provides a text box into which you can enter any expression that the Salesforce formula engine is capable of processing.
  2. Builder Mode provides a point-and-click way to assemble an expression with a minimum of manual entry.

To understand expressions in NBA you need to understand the concept of context records. The context record for a particular execution of a strategy depends on where the execution request came from. If the request came from an NBA Component sitting on a Case record page, then the context record will be that particular Case. If the request comes from a self-serve Community portal page, the context record will be the User that’s logged in. When consumers of NBA recommendations send an execution request to the Strategy Engine, they provide a context record Id.

When you’re configuring an NBA strategy (sometimes referred to as “Config Mode” or “Design Time”), your design something that might get hundreds of different unique recordId’s passed into it. So you need a placeholder that will represent those different values. These placeholders are referred to as global resources and are expressed with a dollar sign. “$Record” is the placeholder representing the actual recordId that will be passed in at Run Time.

There are other global resources that you can use:

$User is the current user logged into the session that generated the execution request

$Request contains any arguments that were passed in with the execution request.

Expressing Field Values

You can span from a global resource to its fields like this:


Expressing Relationships

You can span across relationships up to 5 levels like this:


Creating Expressions in Builder Mode

In Builder Mode, you can start an expression from any available global resource:

Understanding “Object Lock-In”

Consider the expression above ($Record.Contact.FirstName). This will work if the recordId passed in at run-time has a relationship to Contact, so you could use this expression in a strategy intended for generating recommendations for a Case page, because Case objects have a built-in relationship to Contact objects. The expression would resolve at runtime into Case.Contact.FirstName.

However, suppose you took that same strategy and called it from an NBA Component that had been placed on a Contact page? In that case the expression would attempt to resolve as Contact.Contact.FirstName. That doesn’t work because Contacts don’t have relationships to Contacts, so an error will be generated.

What this demonstrates is that most strategies are crafted to ‘fit’ a particular object-type. We refer to that as Object Lock-in. One of the most common sources of errors comes when someone attempts to use a Strategy from a page that isn’t a fit for that strategy’s expressions.

Using AutoComplete in Builder Mode

The Builder Mode of Strategy Crafter can provide you with a list of fields to choose from. However, Strategy Crafter can’t read your mind and doesn’t know from which record pages you intend to call this strategy. To give Strategy Crafter the necessary hint, you can use the “Autocomplete assumes incoming record…” drop-down to pick the object around which you want to design your strategy.

The value of this drop-down has no direct impact on your strategy. It only effects which fields will pop up in the expression builder when you start to create an expression.

If you change this setting on an existing strategy, it will not change any of the existing expressions.