In this article we will look at Apex code which will help us fetch list of required fields of an Object in Salesforce.
In Salesforce a field is called required if it meets the following criteria:
- It is not nillable (meaning it cannot have a null value).
- It is createable (meaning it can be populated while creating a record)
Examples include standard fields like “Name” on most objects or custom fields configured as mandatory.
If you remembered in previous article we have looked at various use cases of dynamic Apex. In most of the use cases we have used Schema Class of Apex. In order to fetch required fields in Salesforce using Apex we will use Schema class and its methods.
Apex Code
Have a look at the below Apex class named RequiredFieldsHelper.
public class RequiredFieldsHelper { public static List<String> getRequiredFields(String objectApiName) { List<String> requiredFields = new List<String>(); // Get the SObject describe information if (Schema.getGlobalDescribe().containsKey(objectApiName)) { Map<String, Schema.SObjectField> fieldMap = Schema.getGlobalDescribe().get(objectApiName).getDescribe().fields.getMap(); // Iterate over fields to check required ones for (Schema.SObjectField field : fieldMap.values()) { Schema.DescribeFieldResult fieldResult = field.getDescribe(); // A field is required if it's not nillable and createable if (!fieldResult.isNillable() && fieldResult.isCreateable()) { requiredFields.add(fieldResult.getName()); } } } else { System.debug('Invalid object API name: ' + objectApiName); } System.debug('Required Fields in ' + objectApiName + ': ' + requiredFields); return requiredFields; } }
How it works?
- As you can see above we have a written a method named getRequiredFields which takes Object API name as input and returns list of required fields (API Name).
- We have used Schema.getGlobalDescribe() to check if the object exists in the org or not and avoiding error with invalid API names.
- If the object API name is valid it retrieves the fields of the object.
- Then we iterate on list of fields and check if the field is not nillable and createable.
- If any field match above condition then we add it to the list of requiredFields.
- Finally we return the list of requiredFields.
Usecases
- Data Validation: Validate data before inserting records to ensure required fields are filled.
- Integration: Ensure external system provides all required field values when integrating with Salesforce.
Also, check out the video on How to get all required fields of an Object using dynamic apex in Salesforce?
We hope now you know How to fetch Required Fields of an Object Using Apex in Salesforce. If you have any doubts then let us know in the comment box below.