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?

  • if you debug template before the update does it look as expected? – Phil B Nov 6 '15 at 18:48
  • somewhat related: sfdc.arrowpointe.com/2011/03/28/cloning-records-in-apex - I can recall having to explicitly nullify fields if the source record field was null (this was when I was doing a custom rollback algorithm) – cropredy Nov 6 '15 at 21:37
  • @PhilB template is as expected. – jmrjulian Nov 6 '15 at 21:42
  • @jmrjulian sorry by as expected its displaying the field with a value of null? – Phil B Nov 7 '15 at 2:16

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.