I want to build a list of fields marked required at the schema level. I have tried below snippet, It works great but fails for the field with default values.
Map<String, Schema.SObjectType> m = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get('contact') ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;
for(String f : fields.keyset())
{
Schema.DescribeFieldResult desribeResult = fields.get(f).getDescribe();
if( desribeResult.isCreateable() && !desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate())
{
//This is mandatory/required field
}
}
Note: Should include fields that have default values set.
isDefaultedOnCreate()