Activity Forums Salesforce® Discussions How to get all the required fields of sObject dynamically?

  • Avnish Yadav

    Member
    July 20, 2018 at 12:53 pm

    Hi Prachi,

    Well, Dynamic Apex API does not provide any direct property that will access required field but if any field is required they must have these three properties:-

    a. It is creatable

    b. It is not nillable.

    3. It doesn't have a default value.

    Example:-

    Map<String, Schema.SObjectType> m = Schema.getGlobalDescribe();
    Schema.SObjectType s = m.get('objectname');
    Schema.DescribeSObjectResult r = s.getDescribe();
    Map<String,Schema.SObjectField> fields = r.fields.getMap();

    for(String field : fields.keyset()) {
    Schema.DescribeFieldResult describeResult = fields.get(field).getDescribe();
    if (describeResult.isCreateable() && !describeResult.isNillable() && !describeResult.isDefaultedOnCreate()) {
    System.debug(field);
    }
    }

    Hope this will help.

    Thanks.

  • Parul

    Member
    September 28, 2018 at 5:15 pm

    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 codemap

    Map<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.

Popular Salesforce Blogs

Popular Salesforce Videos