How to find all required fields within an object in Salesforce?

How to find all required fields within an object in Salesforce?

Option 1: Schema Builder

Option 2: Apex

Sample code:

Apex Class:

public class Utility {
    
    public static void checkRequiredField( String strObjName ) {
        
        SObjectType objType = Schema.getGlobalDescribe().get( strObjName );
        Map < String, Schema.SObjectField > mapFields = objType.getDescribe().fields.getMap();
        
        for( String strField : mapFields.keySet() ) {
            
            SObjectField field = mapFields.get( strField );
            Schema.DescribeFieldResult fieldResult = field.getDescribe();
            
            if ( !fieldResult.isNillable() && !fieldResult.isDefaultedOnCreate() ) {
                system.debug( fieldResult.getLabel() + ' is required.' );
            }
            
        }
        
    }
    
}

Code to Execute:

Utility.checkRequiredField( 'Employee__c' );

Output: 

Leave a Reply