0

I have a scenario in which I need to know if a SObject has been loaded with some fields I am about to update. It has been loaded in another code layer, I just get it in input of my method. I am obliged to reload the object to make sure I don't overwrite not loaded fields with a persisted value. Is that correct?

I was hoping getPopulatedFieldsAsMap() would help me identify which field must be reloaded. The problem is null fields are not in the map. I cannot tell the difference between "not loaded" and "null", which forces me to reload the object anyway. Getting null values for null fields would help a lot in this case.

What do you think? Is it worth asking for an enhancement? I'm not very experienced as an Apex dev, so my design could be totally wrong... Or maybe there is a way to do this I haven't found.

  • you could ask for an enhancement via Salesforce Success Ideas - but this kind of behavior change might take years, if ever, to be implemented. I'd rethink your architecture to use Force.com Enterprise Architecture patterns as shown in Trailhead – cropredy Jan 13 '18 at 18:21
0

If you set a field to null in your working code, it will display in the map from getPopulatedFieldsAsMap.

Example:

Account someAccount = new Account();

someAccount.Name = null; 

System.debug(someAccount.getPopulatedFieldsAsMap().keySet());
// Outputs : {Name}

If you query a record, which has a null value stored in a field, it does not show up in getPopulatedFieldsAsMap.

Account someAccount = [
    SELECT ID, Name, Null_Cust_Field__c 
    FROM Account 
    WHERE Id = '001c000001CcZTFBAO'
];

System.debug(someAccount.Null_Cust_Field__c); // null 
System.debug(someAccount.getPopulatedFieldsAsMap().keySet());

// Outputs : {Name, Id, RecordTypeId}

getPopulatedFieldsAsMap will only show fields which have a value from a query, or have been set in the current context of this object.


If you're trying to prevent a race condition between some asynchronous code, and a UI where a user might have changed a value, then you'll have to query your records no matter what, since getPopulatedFields will only reflect changes to the data you have as an object reference, and not in the database itself.

Some extra detail in your question about the situation you are trying to prevent could go a long way towards a better 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.