[SalesForce] How to check isAccessible() for a dynamic list of field names

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?

Best Answer

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);
}