Last active
December 14, 2015 18:39
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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