I have an exhaustive list of custom objects whose API Names and labels does not match. I end up opening each object in order to determine if the label has matching API Name.I want to see the API Name displayed along with label on the result page of custom Objects. Is there a better way to get label for a custom object when its API Name is known?
2 Answers
You can get the label using the DescribeSObjectResult
:
DescribeSObjectResult describe = SObjectType.MyApiName__c;
system.debug(describe.getLabel());
Another common syntax is:
DescribeSObjectResult describe = MyApiName__c.sObjectType.getDescribe();
You can also just one-line it:
system.debug(SObjectType.MyApiName__c.getLabel());
-
I am looking to do it from the platform, not from the code. A soql query will also help.– smhvrtyjCommented Jul 27, 2016 at 18:40
-
You cannot use a query. What do you mean by from the platform?– Adrian Larson ♦Commented Jul 27, 2016 at 18:42
-
When I log into my org I do a search for objects which has more than 500 objects. I know the API Name and want to navigate to that object but I end of opening each object to see if that is the object I am looking for or not.– smhvrtyjCommented Jul 27, 2016 at 18:56
-
1
The OP asked how to handle an
exhaustive list of custom objects
not just 1 at a time.
For built-in sObjects, the Label is usually the same as the API name but with spaces. Unfortunately there are exceptions for example
API Name: OpportunityLineItem UI Label: Opportunity Product
Custom sObjects can be anything, so you'll need to get a map of all of their API names and Labels. Much of that comes out of the box with Schema.getGlobalDescribe();
The code below worked for me to put the API Name next to the Label.
Map<String, SObjectType> sObjects = Schema.getGlobalDescribe();
for (String apiName : sObjects.keySet()) {
// As far as I know all custom sObject API names end in __c
if (!sObjects.get(apiName).getDescribe().getName().endsWith('__c')) {
// Replace spaces with empty string
System.debug(sObjects.get(apiName).getDescribe().getName() + ' - ' + sObjects.get(apiName.replaceAll('\\s+', '')).getDescribe().getLabel());
} else {
System.debug(sObjects.get(apiName).getDescribe().getName() + ' - ' + sObjects.get(apiName).getDescribe().getLabel());
}
}
Now that the SFDX CLI is available however, I would install it and write a fake test that runs the code above and then redirect it to the CLI.
From there, you could further redirect that output to a file, which would be pretty easy to convert to a basic HTML or VisualForce table.
You probably have the same issue with custom fields. There are now browser plugins for Firefox and Chrome which do an OK job of displaying the fields in Classic Mode