2

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.

2
  • 2
    You don't need the condition isDefaultedOnCreate() Commented Aug 23, 2020 at 13:14
  • @HengkyIlawan Make complete sense but removing isDefaultedOnCreate() condition will retrieve system defined fields too. Commented Aug 24, 2020 at 11:26

1 Answer 1

1

You don't need the condition !desribeResult.isDefaultedOnCreate() because it determines if a field would have a default value at record creation.

If you don't need system defined fields, then use isCustom()

if (desribeResult.isCreateable() 
        && !desribeResult.isNillable()
        && describeResult.isCustom()) {

  //This is mandatory/required field 

}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .