Friday, January 24, 2014

Get all the required fields of sObject dynamically

Now time to post related to the schema in salesforce. Generally we use the following methods to use sObject in class.
                             Account acc = new Account();
But some time we need object dynamically.  In that situation we all need of Schema of Salesforce.
Here i am posting some apex code to use schema in calss.

Map<String, Schema.SObjectType> m  = Schema.getGlobalDescribe() ;
Schema.SObjectType s = m.get(so.apiName) ;
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
 }
}

No comments:

Post a Comment