Salesforce: Dynamically determining the field type of a dynamically determined sObject

This solution is quite difficult to find.

Call me crazy but I need to do this from time to time, and every time I do I can’t remember how I did it before! So I then trudge through the API and the Apex docs until I find the answer and that’s no mean feat in this specific case. Well, no more my friends because I’m putting it right here on this very blog!

In short the code below will return (as a String) theย type of field that we’re working with. Neither the name of the object or the name of the field need to be known in advance.

public static String getFieldType(String fieldName){
    // Assume that "sObjectName" is populated elsewhere
Schema.SObjectType t = Schema.getGlobalDescribe().get(sObjectName);
 
Schema.DescribeSObjectResult r = t.getDescribe();
Schema.DescribeFieldResult f = r.fields.getMap().get(fieldName).getDescribe();
 
if (f.getType() == Schema.DisplayType.String){
    return 'String';
} // .... else if
 
return null;
}

2 thoughts on “Salesforce: Dynamically determining the field type of a dynamically determined sObject”

Leave a Comment