Sub topic 5
Checkbox: true or false data
This chapter assumes you can create custom fields in Object Manager and read basic Apex and SOQL. It covers what a Checkbox field stores, the attributes it lacks, how it behaves in formulas, queries and code, and when a different type fits better.
What a Checkbox stores
A Checkbox field holds one of two values: checked (true) or unchecked (false). Through the API it has the type boolean, and in Apex it maps to Boolean.
Three properties set it apart from most other field types:
- It is never blank. Every record has either
trueorfalse. A new record that doesn't set the field gets the field's default value. - The default value is mandatory. When you create the field, you must choose Checked or Unchecked as the default. Most fields let you leave the default empty.
- It can't be Required, Unique or an External ID. Required would mean nothing, since the field always has a value. Uniqueness would allow at most two records.
| Attribute | Checkbox behavior |
|---|---|
| Required | Not available |
| Unique | Not available |
| External ID | Not available |
| Default value | Required: Checked or Unchecked |
| Null in the database | Not possible |
| Length, precision, scale | Not applicable |
Metadata and describe calls
In metadata format, the default is an explicit defaultValue element.
<?xml version="1.0" encoding="UTF-8"?>
<CustomField xmlns="http://soap.sforce.com/2006/04/metadata">
<fullName>Is_Preferred_Partner__c</fullName>
<label>Is Preferred Partner</label>
<type>Checkbox</type>
<defaultValue>false</defaultValue>
</CustomField>Describe calls report the type as BOOLEAN. The standard Contact fields DoNotCall and HasOptedOutOfEmail are checkboxes, so you can inspect them in anonymous Apex.
Schema.DescribeFieldResult doNotCall = Contact.DoNotCall.getDescribe();
System.debug(doNotCall.getType()); // BOOLEAN
System.debug(doNotCall.isDefaultedOnCreate()); // true: the field always gets a default
Schema.DescribeFieldResult optOut = Contact.HasOptedOutOfEmail.getDescribe();
System.debug(optOut.getType()); // BOOLEANUsing checkboxes in SOQL
Compare a checkbox to true or false. Don't compare it to null, because it never holds null.
SELECT Id, LastName
FROM Contact
WHERE DoNotCall = false AND HasOptedOutOfEmail = falseCheckbox filters have very low selectivity. A field with two values splits a large table into two big groups, so a filter on a checkbox alone rarely narrows the query. Pair it with a selective filter, such as an indexed date range or an Id list, when you query large objects.
Using checkboxes in Apex
A field read from a record is always true or false. A standalone Boolean variable in Apex is different, because it can be null.
List<Contact> contacts = [
SELECT Id, LastName, DoNotCall
FROM Contact
WHERE DoNotCall = false
LIMIT 5
];
Boolean wasAsked; // null: a variable that was never assigned
// if (wasAsked) { } // would throw a NullPointerException
for (Contact c : contacts) {
if (c.DoNotCall == false) {
System.debug(c.LastName + ' can be called');
}
}Test a possibly-null Boolean variable with wasAsked == true instead of if (wasAsked). The comparison is safe because null == true evaluates to false.
A record you build in Apex but don't save has a null value for any field you didn't set. Once the record is inserted, the database applies the default value.
Checkboxes in formulas
You can use a checkbox directly as a condition in a formula. Don't write Is_Active__c = TRUE. Use NOT() for the opposite.
IF(AND(Is_Active__c, NOT(Is_Archived__c)), "Live", "Hidden")A formula can also return a Checkbox. This is the usual way to expose a derived true/false value, such as a flag that depends on other fields. The following formula uses the Checkbox return type on Opportunity.
AND(ISPICKVAL(StageName, "Closed Won"), Amount > 100000)A checkbox formula can't be edited by users and is recalculated automatically. That makes it the better choice when the flag must always agree with other data. A stored checkbox that users tick by hand can drift out of sync.
Checkboxes also work as filter criteria in roll-up summary fields. For example, a COUNT roll-up can count only child records where Is_Active__c is true.
When a checkbox is the wrong choice
A checkbox can't say "not answered yet". If the difference between "No" and "we haven't asked" matters, use a picklist with values such as Yes, No and Unknown. An empty picklist value is possible, and a checkbox can't be empty.
Several checkboxes that describe stages of one process are another warning sign. Fields like Is_Submitted__c, Is_Approved__c and Is_Rejected__c allow impossible combinations, such as approved and rejected together. A single picklist named Status prevents that.
For several independent yes/no options on one record, compare checkboxes with a multi-select picklist. Separate checkboxes are easier to filter, report on and use in automation. A multi-select picklist keeps the page layout shorter but is harder to query.
Changing to or from a checkbox
Changing a field's type is limited, and converting data can change values. Before you convert a Checkbox to Text or Picklist, or the reverse, check the allowed conversions in the Salesforce documentation. Then try the change in a sandbox and review the converted values. Formulas, validation rules and Apex that compare the field to true or false can break after a type change.
Common errors
- Comparing to null.
WHERE Is_Active__c = nullmatches nothing useful. Use= false. - Expecting a required checkbox. To force users to tick a box, add a validation rule such as
NOT(Accepted_Terms__c)with an error message. This works because the field is never blank. - Wrong default. A default of Checked silently marks every existing and new record as true. Existing records get the default when you add the field, so confirm the default matches what the business expects.
- Unassigned Apex variables. A
Booleanvariable that was never assigned isnull, even though a record field is not.
Exercise
A team wants to record whether a customer accepted the terms. Sales sometimes hasn't asked yet, and reports must tell "declined" apart from "not asked". Why is a Checkbox a poor fit, and what should they use?
Show answer
A Checkbox has only two values and is never blank, so "declined" and "not asked" both appear as unchecked. Use a picklist with values such as Accepted, Declined and an empty or Not Asked value. That keeps the three states distinct in reports and queries.
Exercise
You need a field that is true when an Opportunity is Closed Won with an Amount above 100000, and it must never be edited by hand. Which field type and return type should you choose, and what formula would you write?
Show answer
Create a formula field with the Checkbox return type, using AND(ISPICKVAL(StageName, "Closed Won"), Amount > 100000). The value is recalculated automatically and users can't change it, so it can't drift from the stage and amount.