0

I would like to get required fields for an object selected on a VF page , how can this be achieved. I have the describe call, but the object input will need to be dynamically fed from the VF page selected object from drop down..

Schema.DescribeSObjectResult r = sobjectfromVFPAGE.sObjectType.getDescribe();

Map<String,Schema.SObjectField> M = r.fields.getMap();

for(String fieldName : M.keySet()) { 
    Schema.SObjectField field = M.get(fieldName);
    Schema.DescribeFieldResult F = field.getDescribe();
    //A nillable field can have empty content. A isNillable Boolean non-nillable
    // field must have a value for the object to be
    // created or saved. 
    // if F.isNillable() is false then field is mandatory
    Boolean isFieldreq  = F.isNillable() ;
    System.debug ('F = ' + fieldName + ' isnul= ' +  isFieldreq);
}
2

Use Schema.getGlobalDescribe() method to make it dynamic. Quoting from documentation:

Returns a map of all sObject names (keys) to sObject tokens (values) for the standard and custom objects defined in your organization.

Assuming this property- sobjectfromVFPAGE returns Object API Name, here is the required snippet:

Map<String,Schema.SObjectField> M = 
    Schema.getGlobalDescribe().get(sobjectfromVFPAGE).fields.getMap();
|improve this answer|||||
0

You have a couple flaws in your premise:

  1. A field is required if its describe returns a value of false when calling the isNillable() method.
  2. A field can be made required in ways that are not reflected via describes, most notably through Validation Rules.

Consider, for example, this simple rule on the Opportunity object:

ISBLANK(Description)

Writing a rule such as the above will in essence make Description a required field. However, your schema based approach will entirely miss it because this mechanic doesn't show up in the schema.

|improve this answer|||||
-1

Use below code. Please see the changes marked as bold : -

**String str = 'Address__c';
Map <String,Schema.SObjectType> gd = Schema.getGlobalDescribe();
Schema.SObjectType sobjType = gd.get(str);
Schema.DescribeSObjectResult r = sobjType.getDescribe();**
Map<String, Schema.SObjectField> M = r.fields.getMap();
System.debug('------'+M);

for(String fieldName : M.keySet()) {
    Schema.SObjectField field = M.get(fieldName);
    Schema.DescribeFieldResult F = field.getDescribe();
    Boolean isFieldreq  = F.isNillable() ;
    System.debug ('F = ' + fieldName + ' isnul= ' +  isFieldreq);
}

i think it will solve your purpose.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.