function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ram123ram123 

dymaic field describe ?

I like to write a util method for field describe, with can describe on given "Object", "Field",  But current apex feature doesn't seems to allow it, 

 

//this one will allow some flexibility in changing field names as per requirement. 

Sobject sobj = new Opportunity();

Schema.DescribeFieldResult f = sobj.get('Status').getDescribe(); 

 

//currently we can do this, but not useful much,

  Schema.DescribeFieldResult f = Opportunity.Status.getDescribe();  

 

 

Thanks

Ram

 

Best Answer chosen by Admin (Salesforce Developers) 
kibitzerkibitzer

You can't (as far as I know) do exactly what you want, but you can come close:

 

Opportunity o = new Opportunity();
Map<String, Schema.SObjectField> M;

// Need one line for each object type to get the correct field map for that object
if (o.getSObjectType() == Opportunity.SObjectType) M = Schema.SObjectType.Opportunity.fields.getMap();

// The map gives you dynamic access to the field token, from which you can get the describe information.
Schema.DescribeFieldResult F = M.get('stagename').getDescribe();
system.debug(F);

All Answers

kibitzerkibitzer

You can't (as far as I know) do exactly what you want, but you can come close:

 

Opportunity o = new Opportunity();
Map<String, Schema.SObjectField> M;

// Need one line for each object type to get the correct field map for that object
if (o.getSObjectType() == Opportunity.SObjectType) M = Schema.SObjectType.Opportunity.fields.getMap();

// The map gives you dynamic access to the field token, from which you can get the describe information.
Schema.DescribeFieldResult F = M.get('stagename').getDescribe();
system.debug(F);

This was selected as the best answer
ram123ram123

I want to find pciklist value on any object , so this not elegant, but we can kind of keep it using it , instead of duplicating code, 

 

public static List<SelectOption> getProductPickList2(sObjectType obj, String field){
Map<String, Schema.SObjectField> prodFieldMap = null;

//this needs to be repeated for objects your looking pick val

if(obj== Product2.sObjectType){
prodFieldMap =Schema.SObjectType.Product2.fields.getMap();
}
Schema.DescribeFieldResult prodFieldDesc = prodFieldMap.get(field).getDescribe();
List<SelectOption> selectList = new List<SelectOption>{new SelectOption('All', 'All')};
for(Schema.PicklistEntry pick : prodFieldDesc.getPicklistValues()){
if(pick.isActive()){
selectList.add(new SelectOption(pick.getLabel(), pick.getValue()));
}
}
return selectList;

 

 

 

Thanks for your help!

 

Ram