Activity › Forums › Salesforce® Discussions › How To Get All The Required Fields Of Sobject Dynamically?
-
How To Get All The Required Fields Of Sobject Dynamically?
Posted by Aman on September 20, 2018 at 3:06 PMHow To Get All The Required Fields Of Sobject Dynamically?
Parul replied 7 years, 9 months ago 3 Members · 4 Replies -
4 Replies
-
Hi,
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 fields 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() ;
for(String f : fields.keyset())
{
Schema.DescribeFieldResult desribeResult = fields.get(f).getDescribe();
if( desribeResult.isCreateable() && !desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate() )
{
//This is mandatory / required field
}
}
Thanks
- [adinserter block='9']
-
HI
I think 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 has below three properties then it is the mandatory field.
1. If it is Creatable
2. If it is not nullable and
3. If it does not have any default valueThanks
-
Hi,
One more way to do it ,
Try Meta data api to get required fields on particular sobject.
Hope this helps.
-
Correct use can use metadat Api
Here is the ex:
public static Map<String, Schema.DescribeFieldResult> getFieldMetaData( Schema.DescribeSObjectResult dsor, Set<String> fields) { // the map to be returned with the final data Map<String,Schema.DescribeFieldResult> finalMap = new Map<String, Schema.DescribeFieldResult>(); // map of all fields in the object Map<String, Schema.SObjectField> objectFields = dsor.fields.getMap(); // iterate over the requested fields and get the describe info for each one. // add it to a map with field name as key for(String field : fields){ // skip fields that are not part of the object if (objectFields.containsKey(field)) { Schema.DescribeFieldResult dr = objectFields.get(field).getDescribe(); // add the results to the map to be returned finalMap.put(field, dr); } } return finalMap; }
Thanks
Log In to reply.