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.
templateand its Id set to
NumberOfLocations__cvalue to be nullified.
NumberOfLocations__cvalue remains unchanged.
How do I resolve this?
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);
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.