Five Best Practices for Building a Clean Visual Flow

We’ve all been there, where you’re learning to write your first Visual Flow.  The main thing we’re focused on is just making sure that it is functional.  That’s fine while you are in your Sandbox developing, but once you’ve got it working correctly you need to make sure your Flow follows these five best practices.

Elements are Organized

One of the top rules for writing code is using proper indentation.  David Liu (SFDC99) is known for his love (or OCD) of clean code.  Visual Flow’s equivalent to indentation is the alignment of the elements into a clean format.  Think of it like you’re having company over – you would make sure you cleaned your house up before they arrived.

Your Flow should be very easy for you to follow the Flow Elements from start to finish without having to strain your eyes.  Keeping it clean also lets your Flow be easier to make future updates to it.  You don’t have to take apart your Flow to make sure you didn’t miss anything on your update.  So, be sure you spend the extra minute or two to make sure your Flow is sharp looking!

Bad

Messy Flow

Good

Sharp Flow

Naming Convention

In the developer realm, camel Case is the standard.  In Flow, we’re stepping into the developer world without really having to write code.  It obviously isn’t required that you use camel Case as your naming convention, but it is important that you follow a consistent naming convention.  If you don’t, your Flow will be much harder to read.

camel.png

Variable Names

In addition to your naming conventions, you need to make sure your variable names make sense.  I have opened up way too many Flows that use variable names that are not clear. If someone has to do some detective work to figure out what your variable is doing, you need to rethink your variable naming.  Variable naming can often be hard to do correctly, because you have to summarize the function of the variable into a small concise variable.

DoCaseId — Don’tRecordId

Why? RecordId is very generic and does not tell me what Object it is referring to.  I would have to go find where the value was assigned to see the Object it is the Id for.  CaseId is clear and I don’t have to do any research to figure out what it is.

Fault Messages

When your Flow fails its important for everyone to be alerted.  If you’re a Solo Admin, then you can technically get away without using a Fault Message, because Salesforce’s Email Alert will go to you.  However, if you have more than one person developing in your Org, this is a requirement! By setting up a Fault Message, you can easily alert all of the Admins and Developers of the issue.

It is also important to use multiple Fault Messages inside your Flow.  You’re able to customize the Email being sent out to provide specific information that pertains to that particular part of your Flow.  This will help you as you troubleshoot your Flow.

Fault Message

 

Descriptions

Make sure you use Descriptions in your Visual Flow.  This goes along with having your Flow Elements all aligned and easy to read.  You want your Flow to be easily digestible.  It is important to not write blatantly obvious Descriptions, just to write them.  You want to make your Descriptions helpful.

Anytime you have to do something unique inside your Flow you should include a Description to explain what, and more importantly why.  An example would be when you use a Formula in your Flow.

Description.png

 

 

Recap: Think long term when you’re building your Flows (or anything).  Just like you want to create a good User Experience for your End Users, make sure you create a good one for the Admins & Developers that are maintaining the Org.  None of these best practices require a significant amount of time to follow, and the benefits of having a clean Flow will be worth the extra effort!  And if you’re still reading, make sure you check out my The 6 Most Common Visual Flow Errors to Avoid.

 

 

Understanding how to write Process Builder Criteria

I am working on a mini-series related to understanding Bulkification (related to Process Builder and Visual Flow).   So, you’re going to see a theme of posts like this and Building your Process Builder for Optimum Performance and Bulkification where I focus on some design considerations with Process Builder and Flow.  The reason behind these posts are because Process Builder and Flow are extremely powerful tools that give those previously developer-only powers to the masses.  And as we all know… with great power comes great responsibility!  So, lets do our part to make sure that we build our Process Builders and Flows in a way that would not cause developers headaches.  I’ll cover the basics of the different types of criteria, and then go over why it matters that you take building criteria seriously.

spiderman1.jpg

When setting the criteria for our Process Builder to fire, our options are:

  1. Conditions are met
  2. Formula evaluates to true
  3. No criteria – just execute the actions!

Lets dive deeper into each of these and talk about when and why would use them, and some of the common mistakes that are made around these.

Conditions are met

criteriapb.jpg

Using this as our criteria gives us a few more options than what we used to have with Workflow Rules criteria.  Now, we have operators like Is changed and Is null that were previously unavailable to us.  Outside of those new options it is essentially just a cleaner UI.  Don’t forget about the ability to make your Value a Formula (see condition #3), you can use awesome functions like PRIORVALUE and grab in cool System things like your Custom Settings!  Speaking of, Jennifer Lee has a great post on using Custom Settings in Process Builder that is a must read for anyone not familiar with Custom Metadata or Custom Settings!

Conditions.jpg

So we can pretty much do pretty much everything inside this criteria option… but what are the pitfalls that we will run into?

Forgetting to check the Advanced checkbox.

I really wish that Salesforce didn’t hide this section, it needs to be front and center!  I feel like this is one of the biggest errors that people make when building a Process Builder.  It is often overlooked until you’ve got a Process Builder that is creating a record or sending an email, and you realize that you’ve just had six emails get sent out to a Client!criteriaadvanced.jpg

Using Is changed

While I absolutely LOVE this operator that Salesforce gave us within Process Builder, the fact of the matter is I have seen tons of Success Community questions where people get stuck on this.  It isn’t documented very well that Is changed will ONLY run on Updates.  This will not run on Create.  That means, you’re up a creek without a paddle if you’re trying to build your Process Builder to only fire when a value changes, but also have it work if that field has been filled out on create.  If anyone has a clever way that they’ve found to bypass this issue, I’de love to hear it.

Formula evaluates to true

criteriapb2.jpg

While not as simple as the conditions are met option, this gives us the ability to do everything that we would want to do.  The problem is that this often is more fragile than the rest.

API Field Name Changes

This option unfortunately will NOT update your formula if you have to change the field name.  Keep this in mind, because just about everywhere else in the UI this is something we’re accustomed to.  You will however be greeted with a lovely error message anytime you try to Clone ur Update your Process Builder

errormsg.jpg

Is changed for new records works!! kinda…

Here is a simple example of how you could use the formula evaluates to run on new records and still run ischanged on updates.

We essentially have separated our criteria into On record create and On any updates.

(ISNEW() && NOT(ISBLANK(field)) || ISCHANGED(field)

In my below example I only have to use ISNEW() because the Case Status is always filled out.

ischanged.jpg

No criteria – just execute the actions!

criteriapb3.jpg

This should not be used unless you have a very good reason.  Just because we have a simple action does a Record Update and nothing else does not mean that we want it to always fire on every edit.  This means that every single edit our Process Builder is firing.  How many situations can you think of that actually require a Process Builder to fire every single time?  Don’t be a lazy Admin and use this option just because you can!

Why does this matter?

Because of how Salesforce ‘bulkifies’ our Process Builders and Flow!

bulk.jpg

https://releasenotes.docs.salesforce.com/en-us/winter16/release-notes/rn_forcecom_process_bulkification.htm

The issue is that as we continue to customize an Object with more and more Process Builders and Flows you keep adding to the string length!  Remember that every simple Record Update in your Process Builder, no matter how simple, counts as an actual query that will be added into that ‘bucket’.  Previously with Workflow Rules you never had to worry about those simple Field Updates running on every edit of the record, but now as we try to keep our Process Builders and Flows bulkified it becomes an issue!

By fully understanding our Process Builder’s criteria (and using it correctly), we are able to cut back on the extraneous actions.  This results in two big things:

  1. Reduced process time when you hit Create or Edit a record
  2. You’re more bulkified due to a decreased the number of queries

Which means you’re now the hero of your Org!

hero.jpg

How to use a Loop inside a Loop (in Flow)

This past week I saw multiple comments about using a Loops, and one in particular around doing a Loop inside of another Loop.  It is a pretty rare thing that you’ll do with Flow, because of the limits that you’re going to be dealing with, it is very easy to hit a wall with this solution.  Your second Loop is very inefficient, and has to run for every record that is found in the first Loop (which means a Fast Lookup/Query).  This SOQL queries limitation has been improved, prior to writing this blog I thought the limit was 50, but it seems Salesforce recently improved that limitation to 100.

So, keep your limits in mind when you begin to architect a solution like this.  Sometimes it can’t simply be done safely with Flow and you need to move to Apex.

limitsflow

Note: I know that you can add a Formula Field that brings the AccountID to the Campaign Member, but this is a simple example that gets the main point across.

Business Case:

  • When we lose a Client and mark them as a Former Client we want to remove all of their Contacts from all of their Campaigns

Process Overview:

  1. Account Record Meets Criteria – Process Builder triggered (Pass inputs into Visual Flow)
  2. Flow Finds ALL Contacts Associated to Account
  3. Flow Finds ALL Campaign Memberships for ALL Contacts
  4. Flow Deletes ALL Campaign Memberships for ALL Contacts

 

Now, because I’ve already done a post on Fast Lookups and Loops, I am not going to really dive into the individual pieces of this Flow.  I am going to give an outline of what each Element is doing, but I will only be focusing on the areas that are key to understanding how you can use a Loop inside of a Loop.

First, we are going to start out our Flow by looking for ALL of the Contacts related to our Account.  All we need to do is pass in our Account ID into the Flow so that we have that as a Filter.

First Element.jpg

FastLookup1.jpg

Next, we need to now Loop between each of the Contacts that we have found with our Fast Lookup, so to do that we need to drag in our Loop.

Second Element.jpg

Loop1.jpg

Now, this gets us to our Second Fast Lookup, which is where the magic happens.  In here, we simply need to take a step back and think about what we are trying to filter.  In this case I am trying to find all of the Campaign Memberships associated to a particular Contact (so that I can add them to a collection and then eventually delete them).  So, in my Fast Lookup I should be using my Looped Variable to bring in the Contact’s ID.

Third Element.jpg

FL in Loop 0.jpg

FL in Loop 1.jpg

Just like that, we are dynamically filtering this Fast Lookup for each Contact that comes into our Loop!  Pretty simple, right?  All that is left for us now is to setup our next Loop and talk about what we are doing there.

For each Campaign Membership our Contact has, we will be sending them through our next Loop.

Fourth Element.jpg

CampaignMember.jpg

Next, we want to assign the Loop Variable to another SObject Variable, our first step in creating a SObject Collection Variable.

Fifth Element.jpg

Assignment1

Now, we want to assign the SObject Variable to our SObject Collection Variable.

Sixth Element

Assignment2

So we just completed our Loop for the Campaign Memberships!  Awesome!  But, what happens when that Looped Contact has no more Campaign Memberships for us to Loop through?  This is where I’ve seen many people mess up there Flows (including myself every once and a while!), because there is typically a lot going around.  You need to correctly map your second/inside Loop to your first/outside Loop!  This is where we then repeat the process for every Contact that we had in our first Fast Lookup.

Loop to Loop.jpg

Great!  Now, all that is left is for us to determine what happens at the end of our First Loop.  In this scenario we want are sending them to a Fast Delete to get removed in bulk!

Seventh Element

FastDelete.jpg

Great, we are all set!  All that is left for us is to build our Process Builder to launch this Flow.

RECAP:  Loops inside of Loops are powerful features that can let bend the limits of Flow.  These should be used sparingly when you know your inside Loop won’t be used in a high enough volume that you’ll hit a transaction limitation with your Flow.  If you’re getting not confident that you’re going to stay away from that limitation, you should consider building this in Apex instead.  As you could imagine with a scenario like the one above, if we had any Accounts with upwards of 100+ Contacts we would be in some trouble! Beware of the limits!

How to bypass User Permissions with Flow

Have you ever come across a permission limitation that you couldn’t solve using a Permission Set?  Every once and a while we get requirements that can test the limits of what we can technically do with Salesforce.  It might be a Field Level Security issue, or it might be a License limitation.  Before Process Builder was around, if you wanted to get by some sort of limitation like this, you had to write code.  Not anymore!  Process Builder runs in the context of the System.

So… when Visual Flow is that when its autolaunched by Process Builder, it too will run in the context of the System and not the Running User.  This means any Field Level Security, Profiles, Roles, or License type can essentially be ignored.  Think of an Autolaunched Flow as temporarily giving somebody temporary Admin access.  Where this can get interesting is when we start to think of all of the different ways we might use this!

ProcessBuilderIcon

Get creative!  You can do all sorts of cool things to bypass Licenses and Security  issues by using Autolaunched Flows.  Here are a two examples to get you thinking:

Site.com Guest User Access

In this scenario we want to send an email to our clients to propose that we close a Case, and in that email present them with a Yes and No button.  If they click the button you want the Case to properly react.  That means we need to have that button click send them to a specific URL (associated to our Site.com) with a unique parameter that matches to our Case.  The problem is we are unable to have an unauthenticated User edit a Case.  We can give the Site.com Guest User access to Create on a Custom Object, and have that Custom Object then trigger a Process Builder to run and find and edit the Case.  There are some obvious security issues, but they can be solved by building your parameter and Flow correctly.

Add and Remove Permission Sets and Public Groups

We want our Marketing Manager to be able to add and remove people to a Permission Set and/or Public Group.  We can create a Checkbox or Picklist on the User Object, and have an edit to that field trigger a Process Builder to launch our Flow where we either add or remove them to the Permission Set and/or Public Group.  Access to this field can be then controlled by a Permission Set or by Profile.  With this, we can essentially delegate any Admin function to any User without given them Admin privileges!

How to track the Case Age of each Status

I’ve been running into many scenarios where people want to track the Age of each status (be it Case or another Custom Object).  We’ve got things like Field Tracking that we can use to get close, but the data isn’t very easy to build dashboards and reports on.  So, my mind immediately went back to one of my first posts and Flows, Case Time Tracking.  In this post we were wanting to see how long the Users had worked on a Case, and not how long our Cases were staying in a status.  But architecturally we’re going to be pretty similar.

Automation Overview:

  1. Case Meets Criteria – Process Builder triggered (Pass inputs into Visual Flow)
  2. Flow Checks to see if existing open Record
  3. Flow Updates existing record if possible
  4. Flow Checks to see if Case is still Open, exists if Closed
  5. If Case is Open, Flow creates new Record

We will be creating a few fields on our Custom Object:

  1. Case [Master-Detail Lookup]
  2. Start Time[Date/Time]
  3. End Time [Date/Time]
  4. Status [Picklist – Mirror Case’s values]
  5. Minutes [Formula, Number, 2 decimals]

For our Minutes Formula we want to use this:

IF ( ISBLANK ( End_Time__c) , 0 , ( End_Time__c – Start_Time__c ) * 1440 )

Depending on your business case, you might want to change this to be Hours or Days instead of Minutes.  Also, you might want to make 

Here is what our finalized Object looks like:

Case Age 2

Now that we have our Object ready, we can go create our Flow (Setup | Create | Workflows & Approvals | Flows).

NewFlow.jpg

The first step is going to be grabbing our Record Lookup.

RecordLookup.jpg

We are going to be doing a Lookup on our Custom Object we just created to track the Status Ages.  We want to first check to see if one is already open on this Case, and if we need to stamp the open record with an End Time.  If not, then we can ignore going to a Record Update and go to a Record Create if the Case Status is not closed.  For our Record Lookup, we need a variable for our Case’s Id and our Existing Status Age Id (our new Custom Object).

var_CaseId.jpg

StatusAgeId

Which gives us our Record Lookup.  If you notice, we are using IS NULL with the Start and End Date fields.  We simply want to find a record that has a Start Date but doesn’t have an End Date.  That would equate to being an open record that we need to update with an End Dat

Record Lookup for Case Status Age.jpg

Set the Record Lookup as our Start Element

startElement.jpg

Now, we want to drag a Decision Element into our canvas to determine if we found a Record in our Lookup or not.

Add Decision to Flow.jpg

Call the Decision Element “Existing Record?”.  For our first Decision Criteria or Outcome to be checking to see if our variable of the Case Status Age is null or not.

Decision in Flow.jpg

Now, we want to drag in a Record Update element to update the existing Case Status Age record, if we found one.

DragOutRecordUpdate.jpg

We will want to use for our criteria the Id of the record we found in our Lookup.  For the fields we will update, we want to use the System variable, CurrentDateTime

RecordUpdateCaseStatusAge.jpg

Update End Date.jpg

Now, lets drag out another Decision Element.  We need to determine if our Case is Closed or not.  If it is Closed, we don’t need to create another record.  If it is Open, then we will create another Case Status Age record.  So, lets call the Decision Element “Case Closed?”.

AnotherDecision.jpg

We want to create a variable called var_CaseIsClosed that will be passed in from the Process Builder.  Note: this is a BOOLEAN field.  We will check to see if var_CaseIsClosed is FALSE.  If so, we will proceed to our Record Create, but if it is TRUE we will let it exit the Flow.

CaseIsClosedBoolean.jpg

CaseIsClosedDecision

Hit OK, and we now get to map our elements together.  Notice, we map our Record Update to our second Decision Element.

MapDecision.jpg

Now we need to drag out a Record Create.

DragOutRecordCreate.jpg

We need to create a variable called var_Status, which just like var_CaseIsClosed, will be passed in through our Process Builder.

var_Status.jpg

We now will setup our other inputs on the Record Create to be our Case’s Id and the Start Date (which we will use the System Variable again).  This is our last element of the Flow, so we don’t need to assign the Record ID to a variable.

CreateCaseStatusAge.jpg

Now, we need to map our Decision to the Record Create.

FinalizedCaseStatusAgeFlow.jpg

Lastly we want to Save and then Activate our Flow!

SavedFlow.jpg

Note: I like to append “- Flow” to my Autolaunched Flows.  This makes things clearer when I am dealing with them on the backend since Flow and Process Builder both are in the Flow metadata folder.

ActivatedFlow.jpg

Fantastic!  Now we need to setup our Process Builder that launches this Flow.  So lets go create a new Process Builder for this.  (Setup | Create | Workflows & Approvals | Process Builder)

NewPBCaseStatus.jpg

We want the Process Builder to fire on our Account, so for our object select Case, and for starting the process select when a record is created or edited.

CaseStatusPB.jpg

Now we need to setup our Criteria.  Unfortunately an ISCHANGED function doesn’t run on new Cases.  So we have to break out the formula editor and use this formula:

ISNEW() || ISCHANGED([Case].Status)

CaseStatusChanged

Now we get to setup our Immediate Action of launching a Flow.  All we need to do is pass in our Case Id, Case Status, and our IsClosed field.  Note: the IsClosed is listed as Closed in Process Builder.  IsClosed is the API Name for that field.

Set Case Status

Hit Save, and then hit Activate up in the top right corner… and you’re done!

How to Create a Conditional Auto Number

Every once and a while there is a situation where we need to have an Auto Number generated, but only for records that meet a certain criteria.  Lets say that we use the Account Number field as our client’s identifier, and we want to automate this process of incrementing it one every time we have a new client.  There are a few different ways that we can solve this, but we’re going to use Visual Flow.

Automation Overview:

  1. Account Meets Criteria – Process Builder triggered (Pass inputs into Visual Flow)
  2. Custom Object Record with Auto Number created in Flow
  3. Lookup value of Auto Number
  4. Update the Account

For this solution we have three different options in how we can do it architecturally (with our Auto Number):

  1. Custom Object
  2. Custom Metadata
  3. Custom Settings

For me, I am going to go with using a Custom Object.  I think that it is the easiest option of the three to implement, and most Salesforce Admins can relate to Custom Objects more than the other two options.  So, what fields do we need create in this Custom Object?  None!  We just need to make sure we set the Name to be an Auto Number.

AutoNumberObject.jpg

HINT: If you ever need to reset the number, you can switch the Name field to Text and then back to an Auto Number and it will let you pick the Starting Number again.

Here is what our finalized Object looks like:

AutoNumberCustomObject.jpg

Now that we have our Object ready, we can go create our Flow (Setup | Create | Workflows & Approvals | Flows).

NewFlow.jpg

The first step is going to be grabbing our Record Create.

RecordCreate1.jpg

We want to select the Client Number Object that we just created, and then remove the row asking us to set a field value.

RemoveField.jpg

Now, we want to create a variable to house the Record Id.

var_ClientNumberId.jpg

CreateClientNumber

Hit OK, and then we want to set this as our Starting Element.

StartingElementCreateClientNumber.jpg

Now, we want to grab a Record Lookup and find the Name (Auto Number) of the record we just created.

AddRecordLookup.jpg

We are going to need to create a variable to store the Auto Number value that we will then Update our Account with.

var_ClientNumber.jpg

FindAutoNumber

Hit OK.  And now drag out the Record Update element.

RecordUpdateClientNumber.jpg

We will be passing into our Flow the Account Id value, and we will want to use that here to filter on our Record Update.  So we need to create the variable to store that.

var_AccountId.jpg

Map the Client Number to the Account Number field, and hit OK.

UpdateAccountAccountNumber.jpg

Connect the elements together to finish our Flow.

CompletedClientNumberFlow.jpg

And lastly we want to Save and then Activate our Flow!

CreateClientNumberFlowSave

ActivateClientNumberFLow.jpg

Fantastic!  Now we need to setup our Process Builder that fires this Flow.  So lets go create a new Process Builder for this.  (Setup | Create | Workflows & Approvals | Process Builder)

CreateClientNumberPB.jpg

We want the Process Builder to fire on our Account, so for our object select Account, and for starting the process select when a record is created or edited.

PB1.jpg

This next step is completely on you for when the record meets the criteria.  For my example we will just use when the Type is now a Customer.  Careful with the Advanced section at the bottom, you aren’t going to want your Process Builder to fire more than once per Account!

NewCustomerCriteria.jpg

Now we get to setup our Immediate Action of launching a Flow.  All we need to do is pass in our Account Id.

PBLaunchFlow.jpg

Hit Save, and then hit Activate up in the top right corner… and you’re done!

 

 

 

How to Submit for Approval in Visual Flow

You have the ability now to submit records for approval in Process Builder.  This is one of those cases where we pretty much have the same functionality in Process Builder as we do in Visual Flow.  So that means, if its a simple submit for approval scenario, Process Builder will be the right tool for you!  However, if you need to try and make it more dynamic or simply fit it into an existing Visual Flow that you are using, then this Static Action will be your new best friend!
Depending on how many Flows, Quick Actions, and Email Alerts you have in your Salesforce, you might not notice the Static Actions section at the bottom of your Palette.  In here you’ll find a list of all three Static Actions.  We are going to be using Submit for Approval.

Great, we found our Submit for Approval., so lets drag it onto our Flow’s Canvas.

DragtoCanvasSubmitForApproval.jpg

If you notice, the only thing that is required for us to submit this for approval is the Record ID we want this to be triggered on.

RecordIdApproval.jpg

More often than not you’ll want to use some of the additional options with this element.

Submit for Approval Parameters.jpg

So, lets take a look at what those other parameters are:

  • Approval Process Name or ID
    • This allows you to enter the approval process Name or ID that you want to start
    • Leaving this parameter blank will cause the first Approval Process where the Entry Criteria is met to be selected
  • Next Approver IDs
    • Can either be a User ID or a Public Group ID
  • Skip Entry Criteria
    • Allows you to skip the Entry Criteria of your Approval Process
    • If you mark this as TRUE, make sure you specify the Approval Process if there is more than one.
  • Submission Comments
    • If you want to add comments that accompany the submission
  • Submitter ID
    • The User who is ‘submitting’ the record for Approval
    • Default is the Running User

Now we are able to set those parameters and when we hit this element the record will be submitted.  The cool part of this is we can also get pretty creative with what happens AFTER it is submitted for approval by using the Outputs tab, and assigning a parameter to a variable to be referenced after the record is submitted.

SubmitForApprovalOutputs.jpg

So, lets take a look at what our Output parameters are:

  • Instance ID
    • ID of the Approval Process Instance.  You can find this Object labeled ProcessInstance.
  • Instance Status
    • The Status of the Approval.  The four values are: Approved, Rejected, Removed, and Pending.
  • New Work Item IDs
    • A record(s) of work item(s) related to the next step.  Note, you can find this Object
  • Next Approver IDs
    • The next User(s) listed as an approver.  Just like the Work Items, this is potentially a collection of Users, so keep that in mind if you’re planning on working with it!
  • Record ID
    • This is the ID of the record that has been submitted for Approval.  Not of much value, which is why you see it listed last 🙂

 

For a quick summary, if you’re doing something basic with submitting for approval, go with Process Builder!  If you’ve got an existing Flow that you want to incorporate Submitting for Approval in, say you’re using a Visual Flow, then this is a great solution for you!