Apex Bug (?) Null Field Values of Cloned Instances Don’t Persist?

I want to take the state of a source record, clone it, and apply the clone to a target record. But I’m encountering an issue in which a null field on the clone does not nullify the field on the target.

Account account1 = [select id, NumberofLocations__c from Account where NumberofLocations__c != null limit 1];
Account account2 = [select id, NumberofLocations__c from Account where NumberofLocations__c = null limit 1];

// Clone account2 and use it to alter state of account1. 
Account template = account2.clone(false, true, false, false);
template.Id = account1.Id;

update template;

In the example above,

  • two accounts are queried: the target, account1, has a defined value for NumberOfLocations__c, while the source,account2, has a null value in the same field.
  • account2 is cloned, template and its Id set to account1‘s.
  • template is updated.

Expected Result

account1‘s NumberOfLocations__c value to be nullified.

Actual Result

account1‘s NumberOfLocations__c value remains unchanged.

How do I resolve this?

Answer

Although I cannot find documentation to support it, from what I have found it appears this is not a bug but by design. What appears to be happening is Salesforce is removing the field all together since it has no value. You can see this in the logs if you debug all 3 variables by adding system debugs to your code:

system.debug('Acct1: ' + account1);
system.debug('Acct2: ' + account2);
system.debug('Template: ' + template);  

Results

If you explicitly set the field to null then redo the system debugs you will see the field and it’s null value printed out.

Similar issue found here.

Attribution
Source : Link , Question Author : Jan Julian , Answer Author : Community

Leave a Comment