Skip to content

Instantly share code, notes, and snippets.

@Oblongmana
Last active December 14, 2015 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oblongmana/5130937 to your computer and use it in GitHub Desktop.
Save Oblongmana/5130937 to your computer and use it in GitHub Desktop.
Output a list of all fields on an object, and whether or not they are required. This isn't 100% accurate, but is useful for doing things faster! Adapted from http://boards.developerforce.com/t5/Apex-Code-Development/Detect-a-required-field-in-Apex/td-p/129693
//Adapted from http://boards.developerforce.com/t5/Apex-Code-Development/Detect-a-required-field-in-Apex/td-p/129693
Map<String, Schema.SObjectField> describeFields = Schema.SObjectType.Bank__c.fields.getMap();
//CREATE A MAP WITH FIELD NAME AS KEY AND A BOOLEAN (Required) AS VALUE
Map<String, Boolean> fieldIsRequired = new Map<String, Boolean>();
Map<String, Schema.DisplayType> fieldsTypes = new Map<String, Schema.DisplayType>();
for(String field : describeFields.keyset()){
Schema.DescribeFieldResult desribeResult = describeFields.get(field).getDescribe();
//IF FIELD IS CREATEABLE AND IS NOT NILLABLE AND IS NOT DEFAULTED ON CREATE THEN ITS REQUIRED
//EDIT: For some reason - name fields (which are required) show up as nillable, and defaulted on create. Which they aren't necessarily
fieldIsRequired.put(field,desribeResult.isCreateable() && ((!desribeResult.isNillable() && !desribeResult.isDefaultedOnCreate() )|| desribeResult.isNameField()) );
}
for(String field : fieldIsRequired.keySet()) {
System.debug(field + ' : ' + (fieldIsRequired.get(field) ? 'REQUIRED' : 'Not Required'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment