[SalesForce] Read Picklist value’s Label from record

I have a picklist field say Partner with one of the value as Salesforce (Label) and API name is SFDC. When a record is created with this picklist value and queried then it would return the API name (here its SFDC) but would like to read the label thru Apex code, how is it possible? I do not want to use any formula field that return the label value or use toLabel in SOQL. Thanks.

Best Answer

You can get at the picklist value labels by exploring the "describes" information for your given object.

// Schema.SObjectType.Account gets you the SObjectDescribeResult
// From there, fields.Name gets you the fieldDescribeResult
// fieldDescribeResult provides a getPicklistValues() method
List<Schema.PicklistEntry> picklistEntries = Schema.SObjectType.Opportunity.fields.StageName.getPicklistValues();

for(Schema.PicklistEntry ple :picklistEntries){
    // Schema.PicklistEntry provides getLabel(), getValue(), and a few other methods
    system.debug(ple.getLabel());
    system.debug(ple.getValue());
}

The documentation on Schema.PicklistEntry provides a little more detail.

In my example, you could use Opportunity.StageName.getDescribe() instead of Schema.SObjectType.Opportunity.fields.StageName, but other than being shorter to type, I'm not sure of the pros/cons to each approach.

Of course, the above only works if you know both the object and the API name of the picklist field at compile time. If you need something a little more dynamic...

String sobjName = 'Opportunity';
String objField = 'StageName';

List<Schema.DescribeSObjectResult> describeResults = Schema.describeSObjects(new List<String>{sobjName});
system.debug(describeResults[0].fields.getMap().get(objField).getDescribe().getPicklistValues());

The furthest back I could confirm that these will work is v32.0 (Winter '15)

Related Topic