How to tell whether a field is required or not in Apex by describe fields

I want to know how I tell whether a field is required or not in an Apex controller.

In my controller I get the record id and then get the object of that record by a describe call, then I get all the fields of that object, but I am not able to tell which field is required and which is not.


Schema.DescribeSObjectResult r = User.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);

Isnillable identifes whether the field is mandatory or not .If nillable then not mandatory else mandatory.

Source : Link , Question Author : D-Horse , Answer Author : Detached

Leave a Comment