How to get fields for sObject using Apex?

How to get fields for sObject using Apex?

In order to get all fields of an Object in Salesforce, getGlobalDescribe() and getDescribe() from the Schema class can be utilized or we can query the FieldDefinition entity.

Sample Code:

public String obj = 'Account';
Map < String , Schema.SObjectType > globalDescription = Schema.getGlobalDescribe();
Schema.sObjectType objType = globalDescription.get(
	obj
); 
Schema.DescribeSObjectResult objectResult = objType.getDescribe(); 
Map < String , Schema.SObjectField > mapFieldList = objectResult.fields.getMap();  

for ( Schema.SObjectField field : mapFieldList.values() ) {  

	Schema.DescribeFieldResult fieldResult = field.getDescribe();
	
	if(fieldResult.isAccessible()) {  
	
		System.debug(
			'Field Name is ' + 
			fieldResult.getName()
		);
		
	}  
	
}

FieldDefinition can also be used to get all the fields for an object in Salesforce. Check the following Sample Code for reference.

Sample Code:

EntityDefinition objED = [
    
    SELECT DurableId
    FROM EntityDefinition
    WHERE DeveloperName = 'Account'
    
];
List < FieldDefinition > listFieldDefinitions = [
    
    SELECT QualifiedAPIName
    FROM FieldDefinition
    WHERE EntityDefinitionId =: objED.DurableId
    
];

for ( FieldDefinition objFD : listFieldDefinitions ) {

    System.debug(
        'Field Name is ' +
        objFD.QualifiedAPIName
    );

}

Leave a Reply