Posts Tagged ‘Dynamic Apex’
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; }
Instantiating an empty list of SObjects
You’re building a dynamic Apex class so general you’re thinking about promoting it to colonel. You’ve slogged through the Salesforce documentation on the topic, a feat in itself, but are having issues instantiating an empty list of SObjects to be processed in some way.
If you attempt to do this in the seemingly Salesforce manner i.e.
List<SObject> sobjects = new List<SObject>();
You will receive the following error: Compile error: Only concrete SObject lists can be created
This can be rather frustrating as this type of data structure is one of the more commonly used. There are however 3 workarounds, one slightly more elegant than the rest.
NB myObject is a SObject.
List<SObject> sobjects = Database.query('select id from ' + myObject.getSObjectType() +' where id=null');
String searchquery='FIND\'xxx\'IN ALL FIELDS RETURNING '+ myObject.getSObjectType() +'(name)'; List<List<SObject> searchList=search.query(searchquery); List<SObject> sobjects = searchlist[0];
or finally you could use a wrapper class (I’m a huge fan of wrapper classes on this platform)
List sobjects = new List(); public class myObject{ sObject obj {get; set;} public myObject(sObject obj){ this.obj = obj; }
Gratefully this is not a problem you will encouter often, but it is a complex area that can be further complicated by workarounds. But what doesn’t kill you (usually) makes you stronger.