function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RedSalesRedSales 

How to find Required Fields For An Object?

Hello,

 

I've been trying to find out the required fields for some objects but was not sure how I could do this.  For example the User object has details specified as follows  http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_user.htm#topic-title  How can I find out from this though which fields are actually required fields when creating a new user & which are not?

 

Thanking you in advance for your help!

Best Answer chosen by Admin (Salesforce Developers) 
Shashikant SharmaShashikant Sharma

Use this code

 

 

Schema.DescribeSObjectResult r = systemObjectType.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() 
 

 

All Answers

Ritesh AswaneyRitesh Aswaney

For starters, just worth mentioning that some fields might be required at the object level and some others on the page layout level. If your interaction is limited to via the API, then the Page Layout mandatory fields dont apply.

 

Didn't think it was possible to programatically ascertain mandatory field for an object. Just having a look at the Describe Field Result, and there doesnt seem to be a isMandatory or isRequired method 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_fields_describe.htm

Shashikant SharmaShashikant Sharma

Use this code

 

 

Schema.DescribeSObjectResult r = systemObjectType.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() 
 

 

This was selected as the best answer
RedSalesRedSales

Thank you Ritesh, it is the object level I am interested in & not the page layout level. I presume there must be some way of finding this out alright. Thank you again for your help. I guess somebody might know if this is possible. It will be interesting to find out.

 

Thanks again.

RedSalesRedSales

Thanks Shashikant, I will try this out.

RedSalesRedSales

Thanks again folks for the help,

 

The following based on Shashikant's suggestion works.

 

 

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);
           }

 

Ankit AroraAnkit Arora

So basically Shashikant's message should be marked as solution, I am doing same hope you won't mind.

 

 

Thanks
Ankit Arora

 

RedSalesRedSales

That's fine Ankit, I was thinking that Shashikant's message should be the solution but as I modified it slightly I just thought I'd highlight the change that worked to others viewing the post.  Apologies Shashikant's & thanks for your help. I think there should be an option added to the forum to accept more than one response as a solution.

 

Thanks all for the help.

Ankit AroraAnkit Arora

I agree with you that there should be a option to mark more than 1 solution as one is for the original contributor and other is for the final answer. Hope admins will consider this.

 

 

Thanks
Ankit Arora

 

JesalJesal
Without using a Controller, the following markup can be used to display required fields:

<apex:pageBlockSection title="Dimensions">
              <apex:repeat value="{!fields}" var="f">
                  <apex:inputField value="{!merch[f.fieldPath]}"
                      required="{!OR(f.required, f.dbrequired)}"/>
              </apex:repeat>
          </apex:pageBlockSection>

Developer docs: http://www.salesforce.com/us/developer/docs/pages/Content/pages_dynamic_vf_field_sets.htm
JasonICJasonIC
Another super simple method is to use https://workbench.developerforce.com to insert a single record of the Object type in question. The following screen displays the object-level required field(s) in red.
Shekhar P V PalwankarShekhar P V Palwankar
@JasonIC - Nice solution in case someone wants to check the mandatory fields for a specific object. Thanks for sharing.
Matthew BuckmanMatthew Buckman
@JasonIC - Thanks! That is the type of solution I was searching for.
Jesse RoshanJesse Roshan
Account Required Fields List

Below is a modified version which gives us the Field Labels and APIs in a key-value format. 

Schema.DescribeSObjectResult r = Account.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() ;
    if(isFieldreq == false){
        //System.debug ('F = ' + field + ' isnul= ' +  isFieldreq);
        System.debug (F.getLabel() +': ' + field );

    }
}
SFDCMiesterSFDCMiester
Heres another version that I had used for a requirement, Incase anyone needs it. The required fields are put in a map against the Objectname

Output:
Account=(Id, IsDeleted, Name, OwnerId, CreatedDate, CreatedById, LastModifiedDate, LastModifiedById, SystemModstamp,...),
Contact=(Id, IsDeleted, LastName, Name, OwnerId, DoNotCall, CreatedDate, CreatedById, ...)
//get requiredfields for usergiven sObjects
List<String> sObjList = new List<String>{'Account','Contact'};
Schema.DescribeSObjectResult[] descResult = Schema.describeSObjects(sObjList);
Map<String, List<String>> objToRequiredFieldsMap = new Map<String, List<String>>();

for(Schema.DescribeSObjectResult dsr : descResult){
    List<String> requiredFields = new List<String>();
    //get required fields
    Map<String, Schema.SObjectField> fieldMap = dsr.fields.getMap();
    for(String str : fieldMap.keySet()){
        Schema.DescribeFieldResult f = fieldMap.get(str).getDescribe();
        if(!f.isNillable()){
            requiredFields.add(f.getName());
        }
    }
    objToRequiredFieldsMap.put(dsr.getName(), requiredFields);
} 
System.debug(objToRequiredFieldsMap);

 
Punit MisraPunit Misra
Nice solution @JasonIC. While trying this I found that we can even simply browse the objects and their fields and check for thier isNillable property.
But I also wonder why Salesforce don't make this info visible in the Object Manager --> Field and Relationships screen
Kiko CarisseKiko Carisse
You can use the schema builder. In Lightning, go to the Object Manager, then click on Schema Builder. The required fields will have a red line beside them.
jvercejverce
This answer is inaccurate. There are fields that are marked as nillable but are in fact required, and viceversa.

Take for instance the ServiceAppointment object. As per its description metadata, the fields EarliestStartTime and DueDate are required (i.e. they are marked as non-nillable, and also as creatable), and the field ParentRecordId it not required (i.e. it is marked as nillable).

However, the field EarliestStartTime and DueDate are in fact not required to create a ServiceAppointment object, and the field ParentRecordId is in fact required.

This code works:
Account a = new Account(Name='Some Name');
insert a;
ServiceAppointment sa = new ServiceAppointment(ParentRecordId=a.Id);
insert sa;

This code DOESN'T work:
ServiceAppointment sa = new ServiceAppointment(
    EarliestStartTime=Date.parse('2020-11-22'),
    DueDate=Date.parse('2020-11-22')
);
insert sa;

At this moment I'm unable to accurately determine which fields are required for an object. So far, I thought the following formula would work but I've manually verified that IT DOESN'T:
```
function isFieldMandatory(field) {
  return (
    field.createable &&
    !field.defaultedOnCreate &&
    !field.nillable
  );
}
```
jvercejverce
Just to add to my previous comment, the 2nd code snippet fails with the following error:
System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [ParentRecordId]: [ParentRecordId]