Activity › Forums › Salesforce® Discussions › How to get all the required fields of sObject dynamically in Salesforce?
-
How to get all the required fields of sObject dynamically in Salesforce?
Posted by Saurabh on April 27, 2017 at 2:35 PMHow to get all the required fields of sObject dynamically
Parul replied 7 years, 8 months ago 4 Members · 3 Replies -
3 Replies
-
Hi saurabh,
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(so.apiName) ;
Schema.DescribeSObjectResult r = s.getDescribe() ;
Map<String,Schema.SObjectField> fields = r.fields.getMap() ;
List<String> lstrequiredfields=new List<String>();for(String f : fields.keyset())
{
Schema.DescribeFieldResult desribeResult = fields.get(f).getDescribe();
if( desribeResult.isCreateable() && !desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate() )
{
//This is mandatory / required field
lstrequiredfields.add(f);}
}Thanks.
- [adinserter block='9']
-
Hi Saurabh,
You can try this,
public class ControllerClassName
{
public List<String> strList { get;set; }
public void autoRun()
{
Map<String, Schema.SObjectField> objectFields = Schema.getGlobalDescribe().get(‘Account’).getDescribe().fields.getMap();
strList = new List<String>(objectFields.keySet());
}
} -
There is a way to programmatically learn about metadata of your datamodel with in Apex.
Schema Describe calls provides the ability to programitically describe the information about the current org schema such as list of top level objects including custom objects and their fields.Map<String,Schema.SobjectType> gd = Schema.getGlobalDescribe();
We can also use schemaDescribe() to create tree structure of all the objects and fields in the schema browser, to do this we need to use the codemapMap<String,Schema.SobjectType> gd = Schema.getGlobalDescribe();
Returns map of all Sobjects names or Keys to sObject tokens or values for the standard and custom objects defined in the organization.
Log In to reply.