2

I need to iterate over all the fields that I query for a record and check all of those that are custom field checkboxes and see if any are true. The part that I'm not sure how to do is how to iterate over all of those fields after my SOQL query. So just to be more clear, regardless of any changes to the object (a new custom field gets added or an existing one gets removed) or even any changes to the SOQL in terms of adding new fields to the query or removing an existing field from the query. My code will still iterate over all of those that have been queried out.

5

You just need sObject.getPopulatedFieldsAsMap():

for(Object value: record.getPopulatedFieldsAsMap().values()) {
  if(value == true) {
    // We found a match
  }
}

If you need to know which field:

Map<String, Object> values = record.getPopulatedFieldsAsMap();
for(String fieldName: values.keySet()) {
  if(values.get(fieldName) == true) {
    // We found a match
  }
}

Note that only checkboxes can return true/false (including formula fields), so there's no need for a describe call.

3
  • sorry if this is off-topic, but I was wondering if there's any difference between if(value == true) and if(value), in this context? Thank you so much for all your help!
    – Bahman.A
    May 4 '21 at 20:53
  • also is it needed to type-cast "value" like: if ((Boolean) value == true) ? Thanks!
    – Bahman.A
    May 4 '21 at 20:56
  • 1
    @Bahman.A We can't use if((Boolean)value) because it might not be a Boolean, nor can we if((Boolean)value == true) for the same reason. This is why I used value == true, because Object can be compared against all types of values, and we check if it equals the Boolean value of true.
    – sfdcfox
    May 4 '21 at 20:59

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.