4

Accordingly to the documentation of isNillable method of Schema.DescribeFieldResult class:

isNillable()

Returns true if the field is nillable, false otherwise. A nillable field can have empty content. A non-nillable field must have a value for the object to be created or saved.

Is it correct to state that a necessary and sufficient condition for a field to be required is that isNillable method returns false? I'm pretty sure that it is a necessary condition but not so sure that it is also a sufficient condition if we take into account also validation rules and triggers.

1 Answer 1

7

First Approach - For the field to be required it has to meet 3 conditions:

  1. is Creatable
  2. is NOT Nillable
  3. is NOT Default on create

So your if condition should be as following:

if(field.isCreateable() && !field.isNillable() && !field.isDefaultedOnCreate()){
// your code
}

Once ’field’ is an element while of DescribeFieldResult.

Second Approach - to cover code in a try catch block. Into the ’try’ you can insert the Object without the field you want to check, if an exception is thrown, check which required fields are mentioned in the error message. In this approach, you have to delete the record once it succeeds to be inserted.

10
  • Could you please expand your answer with some explanations on why the other two conditions should be checked?
    – gvgramazio
    Apr 27, 2019 at 15:00
  • 1
    @gvgramazio About your first question. For example, CreatedDate is not a nillable field since it has value once record is created, but he is not a required field for the client. To avoid these fields, you should add the two conditions I’ve mentioned.
    – Derminal
    Apr 27, 2019 at 15:10
  • 1
    Or, instead of a try-catch, you can use allOrNone=false to make sure you get all the errors.
    – sfdcfox
    Apr 27, 2019 at 15:54
  • 1
    I wonder if this is how the FieldSetMember.getDBRequired value is calculated developer.salesforce.com/docs/atlas.en-us.apexcode.meta/…
    – Phil W
    Apr 27, 2019 at 19:12
  • 1
    @gvgramazio sounds good..
    – Derminal
    May 4, 2019 at 7:57

You must log in to answer this question.

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