When working in apex, sometimes you need field’s label name and API name and other details. Below is a sample code which can be used to fetch details of any object’s field, its Label, its Name(API Name), and an attribute to check if it’s a custom field or no. There are other options too which can be referred as per business requirement.
Below is the code to fetch all fields of Account object and display those field’s Lable, API Name, and a boolean variable to check whether its a custom field or no.
// A String variable to store any objects's API name
String a_Object_API_Name = 'Account';
// Get Map of sObject's schema fields
// Map<API_Name, Schema.sObjectField> - Key is API name.
Map<String, Schema.SObjectField> M_Objects_Schema_Field = Schema.getGlobalDescribe().get(a_Object_API_Name).getDescribe().fields.getMap();
// Loop the keyset of map.
for( String a_Field_Name : M_Objects_Schema_Field.keySet() ) {
// Get the description of individual fields.
// If you do not want all fields details, then you can replace a_Field_Name with any fields API name
// a_Field_Name = 'Standard_API_Name';
// a_Field_Name = 'My_Custom_Field__c';
Schema.DescribeFieldResult a_Field_Description = M_Objects_Schema_Field.get( a_Field_Name ).getDescribe();
// Label of the field
System.debug('-=-=Label:' +a_Field_Description.getLabel());
// API Name of the field
System.debug('-=-=Name:' +a_Field_Description.getName());
// is a field a custom field or standard field.
// true - Field is a custom field
// false - Field is a standard field
System.debug('-=-=isCustom:' +a_Field_Description.isCustom());
// There are many more methods that can be used as per business needs.
// Ref. salesforce developer page 'DescribeFieldResult Class' for all methods.
//Refer Salesforce:DescribeFieldResult link in Resource section.
}
Sample output of 2 fields only,(Cannot display all fields. Its in loop and there are many more fields.)
An example for Standard field.
-=-=Label:Account Name
-=-=Name:Name
-=-=isCustom:false
An example for Custom field.
-=-=Label:Active
-=-=Name:Active__c
-=-=isCustom:true
Resource
can you run this code against a page layout instead of a table object to return the api feild name and label for all field on a given page layout?
LikeLike
So you are looking for some thing which will give you all field in a particular page layout. Right?
LikeLike