How to get Picklist Label instead of API in Apex

Published by

on


When we query any picklist field on any object in Apex, we always get the API name of it but if you want the label of the picklist then you can use ‘toLabel’.

Suppose we have a custom field named ‘Status__c’ on the ‘Contact’ Object, then the below query will give you desired value

Contact con = [SELECT Id, toLabel(Status__c) FROM Contact WHERE Id = ‘1234567890’];
System.debug(‘Label value of picklist>>’+ con.Status__c);
Wait! If you are trying to get the label in Apex Trigger then this won’t work and you will still get the API value of the picklist. So, you need to use schema describe for the same. Follow the below code snippet.
Contact con = [SELECT Id, Status__c FROM Contact WHERE Id = ‘1234567890’];
//To get picklist entries
List<Schema.PicklistEntry> values = Contact. Status__c.getDescribe().getPicklistValues();
Map<String,String> statusApiToLabelMap = new Map<String,String>();
For(Schema.PicklistEntry sp : values){
	//Map to hold Picklist API as Key and Picklist Label as Value
	statusApiToLabelMap.put(sp. getValue(), sp. values.getLabel());
}
System.debug(‘Label value of picklist>>’+ statusApiToLabelMap .get(con.Status__c));

Operator of PicklistEntry:

  • values.getValue()
  • values.getLabel()
  • values.isActive()
  • values.isDefaultValue()

#HappyLearning