0

I'm doing a query which returns always 1 record, but I need to iterate over the fields from that list, how can I do that? I was trying to do the way below but this doesn't work, I really need to iterate over it.

List<Contact> contactList = [SELECT contactAtribute1__c, contactAtribute2__c from Contact where id = :contactId];
Contact atributeFields =  contactList[0]; 

obs: There are more fields then the query above, that is just an example.

1 Answer 1

0

getPopulatedFieldsAsMap() from the SObject class is what you're looking for.

As the name suggests, it gives you a Map<String, Object> where the keys are the api names of the fields, and the values are the values of each individual field.

Something like this should get you going:

Map<String, Object> popFields = atributeFields.getPopulatedFieldsAsMap();
for(String field :popFields.keySet()){
    system.debug('field: ' + field + ' value: ' + popFields.get(field));
}

The downside is that you'll likely need to cast the field value to be able to do anything with it. That may involve getting at the field describe info so you can know which field type you're working with.

1
  • Thank you Derek, I think that's gonna work fine for what I need.
    – user87331
    Commented Feb 11, 2021 at 21:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .