Another Salesforce blog!!!

Salesforce, Apex

How to get all the required fields of sObject dynamically


There is no direct property available in Apex dynamic API to represent the required field. However there is another way to know about it.
If any field have below three properties then it is mandatory field.

    If it is Creatable
    If it is not nillable and
    If it does not have any default value
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
     system.debug('///' + f ); 
   }
}

One thought on “How to get all the required fields of sObject dynamically

  • Shane Steinfeld says:

    Give this a try on the User object, and you’ll see that it returns a lot of fields that you probably aren’t interested in. (userpermissionsmarketinguser, userpreferencesremindersoundoff, etc…)

    I’d recommend adding describeResult.getType() != Schema.DisplayType.BOOLEAN to your conditional, since these are all checkboxes. I -believe- this will work, since checkboxes are defaulted on record creation…even though their isDefaultedOnCreate describe returns false!

    if(fieldDescribe.isCreateable()
    && !fieldDescribe.isNillable()
    && !fieldDescribe.isDefaultedOnCreate()
    && (fieldDescribe.getType() != Schema.DisplayType.BOOLEAN)){
    [do stuff here]
    }

Leave a Reply

Your email address will not be published.

*