5

I'm trying to find required fields for lead object, I want to make sure this correct logic, because its giving field results which are not marked as required.I'm using isNillable() method in field describe to find out the result, below is the sample code.

Map<String, Schema.SObjectField> fieldsMap = Schema.SObjectType.Lead.fields.getMap();
for(String key : fieldsMap.keySet()){
    Schema.DescribeFieldResult result = fieldsMap.get(key).getDescribe();
    if(!result.isNillable() && result.isCreateable()) {
        System.debug(logginglevel.info, '+++++++++ result = '+result.getName());

    }                   
}
2
  • 2
    if added !isDefaultedOnCreate() in if condition, it seems to be working.
    – realnumber
    Jun 19, 2014 at 0:05
  • If that's the case you should post that as an answer to your own question, then you can mark it accepted once enough time has expired (couple of days).
    – Matt Lacey
    Jun 19, 2014 at 3:32

2 Answers 2

5

To identify required fields !isDefaultedOnCreate() is required in addition to !result.isNillable() && result.isCreateable().

Map fieldsMap = Schema.SObjectType.Lead.fields.getMap();

for(String key : fieldsMap.keySet())
{
    Schema.DescribeFieldResult result = fieldsMap.get(key).getDescribe();
    if(!result.isNillable() && result.isCreateable() && !result.isDefaultedOnCreate()) 
    {
        System.debug(logginglevel.info, '+++++++++ result = '+result.getName());
    }                   
}
0

To add more information to this post, here's an example that shows that the proposed formula does not necessarily tell whether a field is required/mandatory or not:

https://salesforce.stackexchange.com/a/326972/90355

In fact, that formula, which I also figured out indepdently (and made me so happy before reality slapped me in the face) outputs some strange results. For the ServiceAppointment sObject for example, it tells that the required fields are these (when in fact the only required field is ParentRecordId):

[
  "EarliestStartTime",
  "DueDate"
]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .