Get all required fields of Salesforce sObject.

In this article we will discuss how to find required fields of an Salesforce Object . The code given here to find required fields is applicable for Standard and Custom Objects as well .

There is no standard build in method available in Salesforce to find List of all required fields .

To demonstrate the concept we have created the Custom Object named as Student , Which is having one required field – *Age .

Find all Standard and Custom required Fields

Now In order to find the field is required or not we can use the isNillable() method . The following code will return all the Standard and Custom required fields.

				
					Map<String, Schema.SObjectType> describe = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> mapFields = describe.get('Student__c').getDescribe().fields.getMap();
for( String fieldName : mapFields.keySet() ) {
    Schema.DescribeFieldResult desribeResult = mapFields.get(fieldName).getDescribe();
    if(!desribeResult.isNillable()) {
        System.debug('Required Field '+  mapFields.get(fieldName));
    }   
}
				
			

Find all Custom required fields

				
					Map<String, Schema.SObjectType> describe = Schema.getGlobalDescribe();
Map<String, Schema.SObjectField> mapFields = describe.get('Student__c').getDescribe().fields.getMap();
for( String fieldName : mapFields.keySet() ) {
    Schema.DescribeFieldResult desribeResult = mapFields.get(fieldName).getDescribe();
    if(!desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate() ) {
        System.debug('Required Field '+  mapFields.get(fieldName));
    }   
}
				
			

We hope this small post helped you . Please subscribe to our Youtube channel.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top