Activity Forums Salesforce® Discussions How To Get All The Required Fields Of Sobject Dynamically?

  • shariq

    Member
    September 20, 2018 at 3:10 pm

    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

  • Parul

    Member
    September 20, 2018 at 6:10 pm

    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 value

     

     

    Thanks

  • shariq

    Member
    September 20, 2018 at 11:01 pm

    Hi,

    One more way to do it ,

    Try Meta data api to get required fields on particular sobject.

    Hope this helps.

  • Parul

    Member
    September 21, 2018 at 3:48 am

    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.

Popular Salesforce Blogs