In this tutorial I have discuss how you can fetch all fields of any standard or custom object in your lighting component. Today I will show you simplest way to get to get all Field Name and Field Label using APEX code.
With the help of Schema class you can easily get Field Names or Field Labels of an salesforce Object .
Let’s see how to use Schema class to get Field Names of an standard Account Object.
Map<String, Schema.SObjectType> detail = Schema.getGlobalDescribe();
for(Schema.SObjectField fields :detail.get('Account').getDescribe().fields.getMap().Values()) {
System.debug('fields '+ fields.getDescribe().getName());
}
We have use Schema.getGlobalDescribe() which Returns a map of all sObject names (keys) to sObject tokens (values) for the standard and custom objects defined in your organization. And we have used fields.getDescribe().getName() to get API name of Object field.
Similarly you can get Field Label of an Object using fields.getDescribe().getLabel() method .
If you want to return labels and names both at a same time then you can create a Map and put these two to your map like :
mapOfNameAndLabel.put(fields.getDescribe().getName(),fields.getDescribe().getLabel());
Watch the following video where I have explain same concept with more details.
Label or API name?
A field has a label, which users see on the page, and an API name, which you use in code and queries. getName() returns the API name and getLabel() returns the label.
Faster code when the object is fixed
If you already know the object, you do not need Schema.getGlobalDescribe(), which loads every object in the org. Use the object token directly.
Map<String, Schema.SObjectField> fieldMap = Account.SObjectType.getDescribe().fields.getMap();
Map<String, String> nameAndLabel = new Map<String, String>();
for (Schema.SObjectField f : fieldMap.values()) {
Schema.DescribeFieldResult d = f.getDescribe();
nameAndLabel.put(d.getName(), d.getLabel());
}
System.debug(nameAndLabel);Use the global describe version from the post only when the object name arrives at runtime, for example from a component.
FAQ
Can I sort the fields?
Yes. Put the names in a List and call sort().
Does it return fields I cannot see?
The map contains all fields. Check d.isAccessible() to keep only the ones the user can read.