4

I have a query like the following (sample) where the query is pulling fields from multiple objects.

list<contact> cons = [select id, lastName, account.name, account.custom_field__c from contact];

How can I dynamically identify the fields in cons using apex?

Thanks

5
  • My goal is to create a method that takes a generic query result and returns a csv file. To do so, I need the ability to interrogate the field names.
    – sberley
    May 17, 2016 at 21:49
  • I don't think what you want can be done... There is no way to get a List<SObjectField> based on a given List<SObject>. You could go the other direction, but that doesn't seem to be what you are asking.
    – Adrian Larson
    May 17, 2016 at 21:53
  • exactly! making it generic is the fun part.
    – sberley
    May 17, 2016 at 22:01
  • when you say "the other direction" what do you mean?
    – sberley
    May 17, 2016 at 22:06
  • Let us continue this discussion in chat.
    – Adrian Larson
    May 17, 2016 at 22:06

1 Answer 1

5

As of "Summer 16", you can Get a Map of Populated SObject Fields:

Get a Map of Populated SObject Fields

Previously, iterating over just the populated the fields of an SObject involved some complicated programming. For example, if you queried an SObject using SOQL, it wasn’t easy to tell which fields were returned. In Summer ’16, we’ve introduced a new method on the SObject class that returns a map of populated field names and their corresponding values:

Map<String, Object> getPopulatedFieldsAsMap()

contains only the fields that have been populated in memory for the SObject instance, which makes it easy to iterate over those fields. A field is populated in memory in the following cases.

  • The field has been queried by a SOQL statement.
  • The field has been explicitly set before the call to the getPopulatedFieldsAsMap() method.

Fields on related objects that are queried or set are also returned in the map.

Reference: Summer '16 Release Notes

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.