Monday, 26 September 2016

A Validation Rule to make text read-only

A Validation Rule to make text read-only

For this scenario, I needed to set something up in Salesforce to prevent a user for editing their comments after they had submitted a record.

The solution required a validation rule.

Enter the Validation Rule

If you haven't used Validation Rules in Salesforce before they are a really useful tool.

There's a lot of information on the official Salesforce documentation page and the Creating Validation Rules Trailhead unit.

For me, one of the most powerful aspects of Validation Rules is Validation rules fire when a user in your Salesforce screen clicks on 'Submit', therefore they help prevent bad data from getting into your ORG.

Validation Formulas

Validation Rules use Formula Syntax to work out whether they need to show an error message to the user.

When the user tries to save the page, each formula asks "is my criteria true?".

If any of the criteria are true, the rule fires and the error message displays.

You can have multiple validation rules on an object and

  1. none, 
  2. one, or 
  3. many of the rules can return true.

Detecting a changed field

In my scenario, I was asked to prevent a user from changing a text field if they had already submitted text before.

Luckily, there's an awesome formula test called ISCHANGED that detects whether the new value is different than a previous one.

The Validation Rule I created for this instance was:
ISCHANGED(Account_Manager_Comments__c ) &&  TEXT(  Status__c  ) != 'Not Submitted'
This formula would be true if a user changes some text that has already been saved AND the status of the form was anything else apart from 'Not Submitted' (the default value).

Screenshot of a Validation Rule configuration screen
Once the Validation Rule formula has been enetered you get to write the error message that appears and even where it appears on the screen.

Then, once you've got the Validation Rule activated it'll simply keep running and checking every record against that same criteria going forward.

Icon from Iconfinder, artist Carlo Eduardo Rodríguez Espino