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; }
Thanks for the great help, it saved my lot of time…I was looking for the same 🙂
Kapil Goutam
October 7, 2012 at 4:17 am
The if loop can be avoided. We can directly print the type simply by using f.getType().name() 🙂
Praveen
December 28, 2012 at 8:46 am