4

I have a list of field names in an array:

String desiredFieldList; //'AccountId, Id, FirstName ... 'etc
String originObjectName; //'Contact', or 'Opportunity' etc

queryString = 'SELECT ' + desiredFieldList + ' FROM ' + searchObjectName + ' WHERE Id=:searchObjectId';
            List<sObject> sobjList = Database.query(queryString);

But for security review I need to check isAccessible() for each one of those fields for the given object. Normally I can do this using something like (Schema.sObjectType.Contact.fields.Email.isAccessible()) {} but in this case, since the list is dynamic, I'm not sure how to go about it. Any ideas?

0

1 Answer 1

9

For a single field as a string, if you know the sObjectType as a string also, you can do:

public static Boolean isAccessible(String sObjectType, String fieldName)
{
    SObjectType schemaType = Schema.getGlobalDescribe().get(sObjectType);
    Map<String, SObjectField> fields = schemaType.getDescribe().fields.getMap();
    DescribeFieldResult fieldDescribe = fields.get(fieldName).getDescribe();
    return fieldDescribe.isAccessible();
}

If you have them as a comma delimited list, you need to do a bit of processing.

public static List<SObject> query(String sObjectType, String commaDelimitedFields)
{
    SObjectType schemaType = Schema.getGlobalDescribe().get(sObjectType);
    Map<String, SObjectField> fields = schemaType.getDescribe().fields.getMap();

    List<String> fields = new List<String>();
    for (String field : commaDelimitedFields.split(','))
        if (fields.get(field).getDescribe().isAccessible())
            fields.add(field.trim());
    String soql = 'SELECT ' + String.join(fields, ',') + ' FROM ' + sObjectType;
    return Database.query(soql);
}
11
  • 1
    Took the words right out of my textarea box.
    – sfdcfox
    Commented Aug 24, 2016 at 20:29
  • Haha! Great minds. :P
    – Adrian Larson
    Commented Aug 24, 2016 at 20:30
  • Thank you! That looks like just the ticket. I didn't know about .get(sObjectType) and get(field).getDescribe() Commented Aug 24, 2016 at 21:35
  • Right, notice that those are just maps, the former being a Map<String, Schema.SObjectType>, and the latter being a Map<String, Schema.SObjectField>. The Schema. bit is optional most of the time (unless you have a naming collision).
    – Adrian Larson
    Commented Aug 24, 2016 at 21:37
  • Actually - there is a small issue: Invalid type: DescribeSObject Commented Aug 24, 2016 at 22:15

You must log in to answer this question.

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