Handling nulls on checkbox fields in Apex

I have a custom object with a couple of checkbox fields. Those fields have a Default Value of “Unchecked”.

How should those fields behave when assigned a null value in Apex?

Simplified example code:

Boolean nullBoolean;
System.assertEquals(null, nullBoolean, 'Expected to be null');

RepType__c rt = new RepType__c();
// Assign the checkbox fields from the variable
rt.IsOrderManagerRepType__c = nullBoolean;
rt.IsAccountManagerRepType__c = nullBoolean;

// Expected to be null, but comes back as false (the default value?)
System.debug('Direct field value: ' + rt.IsAccountManagerRepType__c); 
//System.assertEquals(null, rt.IsAccountManagerRepType__c, 'This assertion will currently fail');

// Shows that the checkbox fields are null
// Confirms checkbox fields are null, not false

insert rt;

Basic Debug output:

Direct field value: false
RepType__c:{IsOrderManagerRepType__c=null, IsAccountManagerRepType__c=null}

JSON debug output:

“attributes” : {
“type” : “RepType__c”
“IsOrderManagerRepType__c” : null,
“IsAccountManagerRepType__c” : null

Exception from insert:

System.DmlException: Insert failed. First exception on row 0; first error: INVALID_TYPE_ON_FIELD_IN_RECORD, IsAccountManagerRepType: value not of required type: : [IsAccountManagerRepType__c]

Note how any direct code access to the checkbox field in Apex gives the value as being false. So if I check it in code it looks fine to insert. However, the debug of the entire object and attempts to use it in DML show the null value.


Answer from support for Case #14025277

R&D has confirmed that this is a documentation issue. The documentation will be updated to clarify this behavior (please see below).

“The expression accessing a Boolean type field on an sObject with simple dot notation is evaluated to true only if the field value is non-null and true. Otherwise it is evaluated to false.”

As you may already know – To check the checkbox value when using null, please use sObj.get(‘fieldname’).

Source : Link , Question Author : Daniel Ballinger , Answer Author : Community

Leave a Comment