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
System.debug(rt);
// Confirms checkbox fields are null, not false
System.debug(JSON.serializePretty(rt));
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.
nillable:false
so one could argue they shouldn't be assigned null :-). But I would agree with your assertion that an sobject field should be treated like any other apex variable when it comes to null and not masquerade as false