Validation Rule using a before-save Flow? Yes!

Validation Rule using a before-save Flow? Yes!

Last Updated on April 28, 2022 by Rakesh Gupta

Let us first understand the Validation Rule and its characteristics.

A Validation Rule allows a System Administrator to define custom logic and error messages to ensure data integrity. The Rule can contain a formula, or an expression, that evaluates the data in one or more fields and returns a value of True or False. For instance, the Rule includes an error message that displays when it returns a value of True indicating that inaccurate data is being entered. Remember, a Validation rule only fires when a record is created or edited

In this article, I talked about many hidden facts that are not well known, about the Validation Rule. For example, I showed how one can use a Validation Rule, to manage requirements, using Custom Metadata types.

While writing the Formula for a Validation Rule one can only reference fields from the parent record. For example, when writing a Validation Rule on Opportunity one can reference fields from Account but not Quote (which is a child of Opportunity) – as shown in the following screenshot: 

Opportunity - Validation Rule

Let us start with a business use case. 

Objectives:

After reading this blog, you’ll be able to: 

  • Understand what is a before-save Flow.
  • Understand when to use before-save vs after-save Flow.
  • How to use before-save Flow to write a Validation Rule. 

Business Use case

Edward Backhouse is a System Administrator at GurukulOnCloud. Edward received the following requirement from his manager – make sure an Account doesn’t have any open Opportunity if its ‘Out_of_busienss__c’ field value is updated to True. 

So, the requirement is, write a Validation Rule such that, if the Account has an open Opportunity then, display the following error message: 

You can’t deactivate an Account that has an open Opportunity. First, update the Opportunity status, to ‘Closed Won’ or to ‘Closed Lost’, and then deactivate the Account.

What is Before Save Flow?

Use before-save updates Flow to accomplish the same goal as Process Builder (After-save Flow) – but, much faster because, each record does not get saved to the database again. Avoiding that extra save procedure means skipping another round of Assignment rules, Auto-response rules, Workflow rules, and other customizations that take time to execute.

Use a Before-save Flow on the following use cases: 

  1. Update fields on new or changed records
  2. Trigger a Validation rule (this is a custom solution not available out-of-the-box) 

Use an After-save Flow on the following use cases: 

  1. Create or update related records.
  2. Access fields like the Last Modified Date field or the new Record’s ID, only populate after the record is saved. 
    1. For example, sending Email alerts. 
  3. Perform actions other than updating the record that launches the Flow. 

Automation Champion Approach (I-do):

Usually, with Salesforce, multiple approaches are available to solve a business requirement. Choose the ones that are simple, straightforward, and consume fewer resources.

Similarly in this scenario, using either a before Apex trigger or Salesforce Flow can solve the above requirement. 

Let us solve this scenario using Salesforce Flow. Before diving further, let me show you a diagram of a Process Flow at a high level. Please spend a few minutes to go through the following Flow diagram and understand it.

Lightning Flow 21.1

Let’s begin building this automation process.

Guided Practice (We-do):

There are 3 steps to solve Edward’s business requirement using Lightning Flow. First an overview: 

  1. Create Two Custom Fields 
    1. Out_of_Business__c
    2. Open_Opportunity__c
  2. Create a Validation Rule 
  3. Salesforce Flow Steps:
    1. Add a Get Records Element
    2. Use Decision Element to check the Collection
    3. Add Assignment – Update custom field Open_Opportunity__c = True 

Step 1.1: Creating a Custom Field – Out of Business 

  1. Click Setup.
  2. In the User Interface, clicks on Object Manager
  3. Navigate to Account | Fields & relationships and click on the New button.
  4. Click on the Checkbox data type.
  5. Enter Field Label the Field Name will auto-populate. 
  6. Click on the Unchecked for the Default Value.
  7. Add field on the Page Layout and grant field access to the desired profiles. 
  8. Click Save.
Lightning Flow 21.2

Step 1.2: Creating a Custom Field – Open Opportunity 

  1. Click Setup.
  2. In the User Interface, clicks on Object Manager
  3. Navigate to Account | Fields & relationships and click on the New button.
  4. Click on the Checkbox data type.
  5. Enter Field Label the Field Name will auto-populate. 
  6. Click on the Unchecked for the Default Value.
  7. Don’t add the field on the Page Layout and grant field access to the desired profiles. 
  8. Click Save.
Lightning Flow 21.3

Step 2: Creating a Validation Rule

  1. Click Setup.
  2. In the User Interface, clicks on Object Manager
  3. Navigate to Account | Validation Rules and click on the New button.
  4. Enter a name in the Rule Name
  5. Error Condition Formula 
    1. Open_Opportunity__c = True && Out_of_Business = True
  6. Error Message
    1. Error Message: You can’t deactivate an account that has an open Opportunity. First, update the opportunity status to Won or Lost then update the account.
    2. Error Location: Out of Business 
  7. Click Save.
Lightning Flow 21.4_New

Step 3.1: Salesforce Flow – Adding a Get Record Element

  1. Click Setup.
  2. In the Quick Find box, type Flows.
  3. Select Flows then click on the New Flow.
  4. Select the Record-Triggered Flow option and click on Next and configure the flow as follows: 
    1. How do you want to start building: Freeform
    2. Trigger the Flow When: A record is created or Updated
    3. Run Flow: Before the record is saved
    4. Object: Account
  5. Select None for Condition Requirements
  6. Drag-and-drop Get Records element onto the Flow designer. 
  7. Enter a name in the Label field; the API Name will auto-populate.
  8. Select the Opportunity object from the dropdown list.
  9. Set Filter Conditions
    1. Row 1:
      1. Field: AccountId
      2. Operator: Equals
      3. Value: {!$Record.Id}
    2. Row 2:
      1. Field: IsClosed 
      2. Operator: Equals
      3. Value: {!$GlobalConstant.False}
  10. How Many Records to Store:
    1. Select All records.
  11. How to Store Record Data:
    1.  Choose the option to Automatically store all fields
  12. Click Done.
Lightning Flow 21.5

Step 3.2: Salesforce Flow – Using Decision Element to check Collection 

  1. Drag-and-drop Decision element onto the Flow designer. 
  2. Enter Label the API Name will auto-populate.
  3. On the First Outcome enter the Label the API Name will auto-populate.
  4. When to Execute OutcomeAll Conditions Are Met
    1. Row 1:
      1. Resource: {!Find_Related_Open_Opportunities}
      2. Operator: Is Null 
      3. Value: {!$GlobalConstant.False}
  5. Click Done.
Lightning Flow 21.6

Step 3.3: Salesforce Flow – Using Assignment Element to update a custom field 

  1. Drag-and-drop Assignment element onto the Flow designer. 
  2. Enter a name in the Label field; the API Name will auto-populate.
  3. Set Variable Values
    1. Row 1:
      1. Field: {!$Record.Open_Opportunity__c}
      2. Operator: Equals
      3. Value: {!$GlobalConstant.True}
  4. Click Done.
Lightning Flow 21.7

In the end, Edward’s Flow will look like the following screenshot

Lightning Flow 21.8

Almost there! Once everything looks good, click the Activate button.

Proof of Concept

Next time, when a Sales rep creates, or updates, an Account that has an open Opportunity – it will display an error message which we defined in the Validation Rule. 

American Airlines which has Open Opportunity

Lightning Flow 21.9 - Account with Open Oportunity

Updating American Airlines account to Out of Business

Lightning Flow 21.10 - Final Outcome

Great! You are done! Feel free to modify it based on your business requirement. 

Going forward use before-save flow to write such validation rule where you have to look for child records, don’t use Apex Trigger.

Things to Remember

  1. The $Record global variable contains the values from the record that triggers the Flow to run. As a result, you don’t have to add a Get Records Element to obtain the record data nor do you need Flow variables to store the record data.
  2. When the Flow changes the values in the global $Record variable, Salesforce automatically applies those new values to the record. So there’s no need to add an Update Records element to save the new values to the database.
  3. Only these elements are supported: Assignment, Decision, Get Records, and Loop.

Formative Assessment:

I want to hear from you!  

What is one thing you learned from this post? How do you envision applying this new knowledge in the real world? 

Let me know by Tweeting me at @automationchamp, or find me on LinkedIn.

Proofreader: - Munira Majmundar
Have feedback, suggestions for posts, or need more information about Salesforce online training offered by me? Say hello, and leave a message!

10 thoughts on “Validation Rule using a before-save Flow? Yes!

  1. Thank you! I love your blog. Very useful feature like before update Trigger.

    You can also implement this functionality without Flow:
    1. Create a Roll Up Summary Field on Account to count number of Child Records (Opportunities). Ex: Let’s Say 2 Child Records
    2. Create a Roll Up Summary Field on Account to count number of Child Records (Opportunities) in Closed Stage. Ex: Let’s Say 1 Child Record
    3. Create a Validation Rule. If number of Closed Opportunities are same as number of Opportunities and Out of Business is True, then don’t show the error message else show the error message.

  2. 🙂 To expand logic, I would suggest taking care of the case, when Account.Out_of_business__c = true and User is creating new Opportunity for this Account. Probably the easiest way is to configure the lookup filter on Opportunity or if we want to show some descriptive Error message, I would go with another validation rule on Opportunity: ISNEW() &&Account.Out_of_business__c = TRUE

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.