2

In the line - objApi.fieldApi.getDescribe().getPicklistValues(), I am trying to pass ObjApi as Object API and fieldApi as Field API in the parameters. So that it will form like this - Account.Industry__c.getDescribe().getPicklistValues(). However, I am getting an error on this line:= Method does not exist or incorrect signature: void getDescribe() from the type String

Please help

 /*TO RETREIVE FIELD PICKLIST FROM OBJECT BY PASSING OBJECT API AND FIELD API
 @param1: STRING - OBJECT API
 @Param2: STRING - FIELD API  
 */
 @AuraEnabled
 public static List<String> getPickList(String objApi, String fieldApi){

    List<string> picklistvalues = new List<string>();

    for( Schema.PicklistEntry pickListVal : objApi.fieldApi.getDescribe().getPicklistValues()){
        picklistvalues.add(pickListVal.getLabel());
    }
     return picklistvalues;
 
    }

1 Answer 1

4

First you need to convert the String (SObjec tName) from String to SObjectType with Schema.getGlobalDescribe().get(objectName). Then use Schema.DescribeSObjectResult,Schema.SObjectField and Schema.PicklistEntry as below to get the Picklist values.

String objectName = 'Contact';
String fieldName ='LeadSource';
  
Schema.SObjectType objSobjectType = Schema.getGlobalDescribe().get(objectName) ;
Schema.DescribeSObjectResult objDescribeSobject = objSobjectType.getDescribe() ;
Map<String,Schema.SObjectField> fields = objDescribeSobject.fields.getMap() ;
Schema.DescribeFieldResult fieldResult = fields.get(fieldName).getDescribe();
List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
for( Schema.PicklistEntry pickListVal : ple){
    System.debug(pickListVal.getLabel() +' '+pickListVal.getValue());
}

Update 1

As Phil W mentioned Schema.getGlobalDescribe is not efficient rather use the following method. You can get the details here.

String typeName = ...; // E.g. 'Case' or 'Account' etc.
SObject instance = (SObject) Type.forName('Schema.' + typeName).newInstance();

Update 2

As Elijah mentioned the above method doesn't support Record Type. Looks like it is not currently possible with native Apex, but there is an Idea you can upvote. As suggested use Tooling API instead.

3
  • 4
    Do not use Schema.getGlobalDescribe. See this for why and how to do the same thing more efficiently.
    – Phil W
    Jul 23, 2022 at 12:38
  • 1
    This doenst take record type in picture. Rather use Tooling api to get this information
    – Elijah
    Jul 23, 2022 at 12:42
  • The Apex PM's suggestion was to use the UI Api to cater for recordtypes
    – cropredy
    Jul 23, 2022 at 21:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .