Sub topic 10
Referencing Related Records and Global Variables
This chapter assumes you can write a basic error condition formula, use AND, OR, NOT and ISBLANK, and handle picklists with ISPICKVAL. You also need to know how lookup and master-detail relationships connect objects. Here you will extend rules beyond the fields on the record being saved.
Why reach beyond the current record
Many business rules depend on data that lives elsewhere. An Opportunity might need an Account to be active. A Contact might need the parent Account to have a billing country. A rule might also depend on who is saving the record, or on today's date. Validation rules can read this data without Apex or a flow.
Two features make this possible:
- Cross-object references, which use a relationship name and a dot to read fields on a parent record.
- Global variables, which expose the running user, the user's profile and role, custom permissions, organization data, and custom settings.
Cross-object field references
A cross-object reference starts from a lookup or master-detail field on the current object. It follows the relationship to the parent and reads a field there. This is called spanning a relationship.
The syntax is RelationshipName.FieldName:
- For standard relationships, use the relationship name, such as
Account.Industryon a Contact or Opportunity. - For custom relationships, the name ends in
__r, such asProject__r.Status__c. The lookup field itself ends in__c, and the relationship name replaces that suffix with__r. - You can chain up to 10 relationships, such as
Account.Owner.Manager.Email. Formulas have a limit of 10 unique relationships per object.
Here is a rule on Opportunity that blocks closing a deal when the parent Account is inactive. It assumes a custom checkbox Active__c on Account:
AND(
ISPICKVAL(StageName, "Closed Won"),
NOT(Account.Active__c)
)The rule is true, and so blocks the save, only when the stage is Closed Won and the Account is not active.
Direction matters: parents only
Validation rules can read upward, from child to parent. They cannot read downward. A rule on Account cannot look at its Contacts or Opportunities. A rule on Opportunity cannot read the Opportunity Line Items as a list.
The exception is a roll-up summary field. It exists only on the master object of a master-detail relationship, and it can summarize child records with COUNT, SUM, MIN or MAX. A rule on the master can then reference that field. For example, if Account has a roll-up named Open_Cases__c, this rule works:
AND(
ISPICKVAL(Type, "Customer - Channel"),
Open_Cases__c > 0,
ISCHANGED(Type)
)For a lookup relationship, you cannot create a roll-up summary field. You need a flow or Apex for child-aware logic. Chapter 15 covers this choice.
Null parents
If the lookup field is empty, every field reached through it evaluates as blank. Text comes back as an empty string, numbers as null, and checkboxes as false. This leads to a common error.
The rule below intends to require a parent Account with an industry of Banking when the stage is Prospecting:
AND(
ISPICKVAL(StageName, "Prospecting"),
Account.Industry <> "Banking"
)Run against an Opportunity with no Account, Account.Industry is blank, so the comparison is true and the save is blocked. Sometimes that is what you want, but often it is not. If a missing parent should be allowed, test for it first:
AND(
ISPICKVAL(StageName, "Prospecting"),
NOT(ISBLANK(AccountId)),
TEXT(Account.Industry) <> "Banking"
)Notice that Account.Industry is a picklist. A picklist reached through a relationship follows the same rules as one on the current record. You must use TEXT() in comparisons and ISPICKVAL() for equality checks. Account.Industry <> "Banking" would fail to save with a type error.
Fields that cannot be referenced
Some fields are unavailable in validation formulas. Long text areas, for example, cannot be used. Fields on a parent that the running user cannot see still work, because validation rules run in system context for field-level security. This is useful but can surprise you: a rule can expose logic that depends on data a user cannot view. Write messages that do not reveal the hidden values.
Global variables
Global variables begin with a dollar sign. These are the ones used most often in validation rules:
| Variable | What it gives you | Example |
|---|---|---|
| `$User` | Fields on the user saving the record | `$User.Id`, `$User.Department` |
| `$Profile` | Fields on the user's profile | `$Profile.Name` |
| `$UserRole` | Fields on the user's role | `$UserRole.Name` |
| `$Permission` | True or false for a custom permission | `$Permission.Bypass_Validation_Rules` |
| `$Organization` | Organization-wide details | `$Organization.Id` |
| `$Setup` | Hierarchy custom settings and custom metadata values | `$Setup.Rule_Settings__c.Max_Discount__c` |
| `$RecordType` | Fields on the current record's record type | `$RecordType.DeveloperName` |
Salesforce also offers date and time functions such as TODAY() and NOW(). These are functions, not variables, but you will use them with the same goal: comparing a record against the current context.
Using `$User`
Use $User when a rule depends on who is saving. This rule lets only the record owner change an Opportunity's Amount after it is created:
AND(
NOT(ISNEW()),
ISCHANGED(Amount),
OwnerId <> $User.Id
)The rule blocks the change when the person saving is not the owner. Compare IDs, not names. Names can repeat or change, but IDs cannot.
Using `$Profile` and `$UserRole`
You can limit a rule to certain profiles by name:
AND(
$Profile.Name = "Sales User",
ISBLANK(Description)
)This works, but it is fragile. If someone renames the profile, the rule stops matching and gives no warning. Prefer a custom permission when you can, because a permission describes a capability and is not tied to a label. The next chapters on record scope and bypass patterns develop this idea further.
Using `$Permission`
$Permission.Name_of_Permission returns true if the running user has that custom permission through a profile or permission set. The name is the custom permission's API name. The variable is true or false, so you use it directly:
AND(
NOT($Permission.Bypass_Validation_Rules),
ISBLANK(Description)
)Using `$Setup`
Hierarchy custom settings and custom metadata types hold configurable values. A rule can then read a threshold instead of a hard-coded number. Suppose Rule_Settings__c is a hierarchy custom setting with a number field Max_Discount__c:
Discount_Percent__c > $Setup.Rule_Settings__c.Max_Discount__cAn admin can change the limit in Setup without editing the rule. Be careful with a hierarchy setting: the value returned depends on the user, their profile, and the org default. If no value is set at any level, the field is null, and the comparison does not behave as you might expect. Guard with ISBLANK when that is possible.
Combining the two ideas
Cross-object references and global variables often appear together. This rule on Case blocks closing a case unless the parent Account has a support tier, and lets users with a custom permission skip the check:
AND(
NOT($Permission.Bypass_Validation_Rules),
ISPICKVAL(Status, "Closed"),
NOT(ISBLANK(AccountId)),
ISBLANK(TEXT(Account.Support_Tier__c))
)Order the clauses with the cheap bypass check first so the intent is easy to read. Formula evaluation does not guarantee short-circuiting in the way a programming language does, so do not rely on the order to avoid errors. Rely on explicit blank checks instead.
Limits and failure modes
- A formula, including the validation rule's formula, can be at most 5,000 characters, and the compiled size limit is 5,000 bytes in many contexts. Deep relationship chains use up this budget quickly.
- Each unique relationship spanned counts toward the limit of 10 per object. Referencing
Account.NameandAccount.Industryuses one relationship, butAccount.Owner.Nameadds another. - Changing a parent record does not re-run validation rules on child records. A rule on Opportunity that reads
Account.Active__conly fires when an Opportunity is saved. If the Account becomes inactive later, existing Opportunities stay as they are until someone edits them. - Polymorphic lookups, such as
Owneron Case (a user or a queue) orWhatandWhoon Task, restrict which fields you can read. Test these rules carefully. - A rule that depends on a hierarchy custom setting will behave differently for different users. Test as each affected user, not only as an admin.
Debugging a cross-object rule
- Create a test record whose parent has the exact values you expect to trigger the rule.
- Create a second record with no parent, and confirm the rule behaves as intended.
- Create a third whose parent has blank values in the referenced fields.
- Save each one as a user who does not hold the bypass permission.
If the formula will not save, read the error message. Typical causes are a missing TEXT() around a picklist, a misspelled relationship name, or __c used where __r is required.
Exercise
Write a validation rule on Opportunity that blocks saving when the Opportunity's Account has a BillingCountry of "USA" but the Opportunity's stage is "Closed Won" and the Account's BillingPostalCode is blank. The rule must not block Opportunities that have no Account.
Show answer
AND( ISPICKVAL(StageName, "Closed Won"), NOT(ISBLANK(AccountId)), Account.BillingCountry = "USA", ISBLANK(Account.BillingPostalCode) ) The ISBLANK(AccountId) check prevents the rule from firing when there is no parent. BillingCountry is a text field, so a plain equality comparison works. This is not a picklist unless State and Country picklists are enabled in the org. If they are, use TEXT(Account.BillingCountry) = "United States" with the matching label.
Exercise
Why is OwnerId <> $User.Id safer than comparing owner and user names?
Show answer
IDs are unique and never change. Names can be duplicated between two people, and they change when someone is renamed, so a name comparison can wrongly allow or block an edit.