The Silver Lining

A developer's view of Cloud Computing platforms & technologies.

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

with 2 comments

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;
    }
About these ads

Written by Wes

February 1, 2012 at 9:33 pm

2 Responses

Subscribe to comments with RSS.

  1. 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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,851 other followers

%d bloggers like this: