1

Attempting to retrieve a field not acquired by soql will result in the following error.

SObject row was retrieved via SOQL without querying the requested field: object.field__c

In order to prevent this error from occurring, we know that we need to add fields that we did not get in soql.

Is it possible to write a process to set a null character in a String variable without getting the above error when trying to acquire an unfetched field?

Refer to the following article Check is SObject has certain field

I implemented the following code, but I got an error.

Public static boolean hasSObjectField (String fieldName, SObject so) {
             Return so.getSobjectType().GetDescribe().Fields.getMap().KeySet().Contains (fieldName.toLowerCase ());
}
1
  • 2
    Checking if the field name is valid doesn't tell you if it has been queried for. You can find out which fields have been queried, which I outlined in an answer below, but you haven't given much of your use case. What are you trying to accomplish, at a high level?
    – Adrian Larson
    May 10, 2017 at 14:41

1 Answer 1

1

One workaround would be to use the getPopulatedFieldsAsMap() method. Unfortunately, that makes your API Names case-sensitive.

User u = [SELECT Id FROM User LIMIT 1];
Map<String, Object> data = u.getPopulatedFieldsAsMap();
system.assertEquals(null, data.get('Name'));
system.assertNotEquals(null, data.get('Id'));
system.assertEquals(null, data.get('id'));
system.assertEquals(null, data.get('ID'));
2
  • Ugh...I really should pay more attention to the release note. Thanks for informing us of this new (summer 16) ability
    – Eric
    May 10, 2017 at 14:49
  • @Adrian Larson♦ It is amazing! It is! Thank you!
    – user40710
    May 11, 2017 at 0:40

You must log in to answer this question.