Sub topic 3
Restricting lookup choices with lookup filters
What a lookup filter does
A lookup field lets a user pick any record of the target object. For a Contact lookup on an Opportunity, that means every contact in the org, including contacts from unrelated accounts. A lookup filter narrows the list of valid choices with criteria you define.
You assume the following from earlier chapters. You know how a lookup relationship is created and what its relationship name does. You can read the field definition screens in Object Manager. You know that a relationship field stores the Id of one parent record.
Lookup filters are declarative (configured in Setup, with no code). They work on lookup, master-detail, and hierarchical relationship fields. Despite the name, they are not limited to plain lookups.
A filter does two things:
- It limits the records shown in the lookup search dialog and the type-ahead suggestions.
- It validates the value when a record is saved. A user who types or pastes a value that breaks the criteria gets an error message.
Where you configure a filter
Open Object Manager, choose the object that holds the relationship field, open the field, and edit it. The field definition has a Lookup Filter section. A filter belongs to one field on one object.
A filter has these parts:
- Filter criteria. Each row has a field, an operator, and a value or another field to compare against. Rows combine with AND by default, and you can write custom filter logic such as
1 AND (2 OR 3). - Filter type. Required or optional. See the next section.
- Error message. Shown when a required filter rejects a value.
- Info message. Shown in the lookup dialog to tell users why the list is shortened.
- Active. You can save a filter as inactive while you work on it.
What the criteria can compare
The left side of a criterion is a field on the target object, or a field reached through a relationship from the target. The right side can be one of these:
| Right-side source | Example | Typical use |
|---|---|---|
| A fixed value | `Account.Type equals Customer` | Offer only customer accounts |
| A field on the record being edited (`$Source`) | `Contact.AccountId equals $Source.AccountId` | Keep a child's choice consistent with its other parent |
| A field on the current user (`$User`) | `Account.OwnerId equals $User.Id` | Offer only records the user owns |
| A field on the user's profile or role, through `$User` | `Account.Region__c equals $User.Region__c` | Offer records in the user's region |
The $Source option is the one that makes filters most useful. A filter with a fixed value is the same for everyone. A filter that references the source record adapts to the record being edited.
Required and optional filters
The filter type decides how strict the filter is.
| Behavior | Required filter | Optional filter |
|---|---|---|
| Lookup dialog | Shows only matching records | Shows matching records first, with an option to show all results |
| User picks a non-matching record | Save is blocked with your error message | Save is allowed |
| Enforced for API and Apex DML | Yes | No, UI only |
| Good for | Data integrity rules | Guidance and convenience |
Choose required when a wrong value would corrupt your data. Choose optional when the filter is only a convenience and some users have a legitimate reason to pick something else.
A required filter is real validation. An insert from Apex or the API that breaks it fails with the status code FIELD_FILTER_VALIDATION_EXCEPTION. An optional filter does not stop data loads or integrations. Do not rely on one to protect data.
A worked example: contacts from the same account
Suppose Opportunities have a custom lookup field Primary_Contact__c that points to Contact. Without a filter, a rep can choose a contact from any account. The business rule is that the primary contact must work at the opportunity's account.
In Setup, add a filter with one criterion:
- Field:
Contact: Account ID - Operator:
equals - Value type: Field
- Value:
Opportunity: Account ID(this is$Source.AccountId)
Set the filter type to required, and set the error message to "Choose a contact that belongs to this opportunity's account."
If you manage metadata in a source-controlled project, the same filter is part of the field's metadata file:
<?xml version="1.0" encoding="UTF-8"?>
<!-- force-app/main/default/objects/Opportunity/fields/Primary_Contact__c.field-meta.xml -->
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Primary_Contact__c</fullName>
<label>Primary Contact</label>
<referenceTo>Contact</referenceTo>
<relationshipLabel>Primary Contact Opportunities</relationshipLabel>
<relationshipName>Primary_Contact_Opportunities</relationshipName>
<deleteConstraint>SetNull</deleteConstraint>
<type>Lookup</type>
<lookupFilter>
<active>true</active>
<errorMessage>Choose a contact that belongs to this opportunity's account.</errorMessage>
<filterItems>
<field>Contact.AccountId</field>
<operation>equals</operation>
<valueField>$Source.AccountId</valueField>
</filterItems>
<infoMessage>Only contacts from this opportunity's account are listed.</infoMessage>
<isOptional>false</isOptional>
</lookupFilter>
</CustomField>The element isOptional set to false makes the filter required. The deleteConstraint value SetNull is the usual lookup behavior: if the contact is deleted, the field is cleared.
You can confirm that the filter is enforced outside the UI. This anonymous Apex tries to link an opportunity to a contact from a different account:
Account a1 = new Account(Name = 'Filter Demo A1');
Account a2 = new Account(Name = 'Filter Demo A2');
insert new List<Account>{ a1, a2 };
Contact stranger = new Contact(LastName = 'Stranger', AccountId = a2.Id);
insert stranger;
Opportunity opp = new Opportunity(
Name = 'Filter Demo Opp',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
AccountId = a1.Id,
Primary_Contact__c = stranger.Id
);
try {
insert opp;
} catch (DmlException e) {
System.debug(e.getDmlStatusCode(0));
System.debug(e.getDmlMessage(0));
}With the required filter active, the first debug line prints FIELD_FILTER_VALIDATION_EXCEPTION and the second prints your error message. If you change the filter to optional, the insert succeeds.
How a filter is applied
Using filters on master-detail and junction fields
Filters are not limited to lookups. On the Enrollment junction object from the many-to-many chapters, the Course__c field is a master-detail field. You could add a required filter such as Course: Active equals true (assuming Course__c has a checkbox field named Active__c). Users can then enroll students only in active courses.
One limit applies to master-detail fields. A filter restricts what you can choose when a record is created or when the value changes. A master-detail field is required, so a filter on it must leave users some valid choice. A criterion that matches no records makes the field impossible to fill. Test every filter on a required field with an ordinary user profile before you deploy it.
Common errors and edge cases
Filters do not change existing data. Adding a filter does not scan existing records or reject values that are already saved. Records that were valid yesterday stay in place. A later edit that touches the field is checked against the filter. Behavior for edits to other fields depends on the filter, so test it in a sandbox if you need a guarantee. If you need to find records that already break the rule, write a SOQL query or a report for them.
A filter is not a sharing rule. The lookup dialog shows only records the user can already see. A filter narrows that visible set further and never widens it. If a user cannot find a record, check sharing and field-level security before you blame the filter.
Optional filters invite bad data. Users who see the "show all results" option can ignore the filter, and integrations can ignore it completely. If the rule matters, make the filter required.
$Source values can change after the choice. If the opportunity's account changes after the contact was chosen, the existing contact value is not automatically cleared. Consider a validation rule or a flow for rules that must hold whenever either field changes.
A filter cannot cover every rule. Filter criteria are comparisons, so filters cannot call Apex or evaluate arbitrary formulas. Use a validation rule or trigger when the rule needs more than field comparisons.
Limits apply. Salesforce caps the number of active lookup filters per object and the number of criteria per filter. Check the current limits in the Salesforce documentation before you plan many filters on one object.
Packaged and deployed filters travel with the field. The filter is part of the field's metadata, so a deployment overwrites the filter in the target org. Review field files in your change set or source diff.
Choosing between a filter and other tools
| Need | Best tool |
|---|---|
| Narrow the choices a user sees and block invalid picks | Required lookup filter |
| Suggest likely choices but allow exceptions | Optional lookup filter |
| Enforce a rule involving several fields or complex logic | Validation rule |
| Enforce a rule that must also fire when a different field changes | Validation rule or automation |
| Keep users from seeing records at all | Sharing settings and field-level security |
Exercise
A Case has a lookup field Related_Asset__c pointing to Asset. You want users to choose only assets that belong to the case's account, and you want a data load through the API to be rejected if it picks an asset from another account. What filter type and criterion do you use?
Show answer
Use a required filter, because only required filters are enforced for API and Apex DML. The criterion compares the target's account with the source record's account: Asset.AccountId equals $Source.AccountId. An optional filter would be enforced only in the UI, so the data load would succeed.
Exercise
You add a required lookup filter to a field that already holds values on thousands of records, and some of those values do not match the new criteria. What happens to those records, and how can you find them?
Show answer
The existing records are not rejected or changed when you add the filter. A later edit of the field is checked against the filter. To find the non-conforming records, run a SOQL query or report that applies the opposite of the filter criteria, then correct the values yourself.
Exercise
An Enrollment junction record has a master-detail field Course__c. A teammate adds a required filter Course__c.Active__c equals true, and now an administrator's Apex test that inserts an Enrollment for an inactive Course fails. What is the failure, and what are two ways to fix the test?
Show answer
The insert fails with a DmlException whose status code is FIELD_FILTER_VALIDATION_EXCEPTION, because required filters apply to Apex DML. Fix the test by creating the Course with Active__c = true before inserting the Enrollment, or by asserting that the exception occurs if the test is meant to check the rule.