DEV Community

GAURAV KUMAR
GAURAV KUMAR

Posted on

How to get required fields of an SObject in Apex

Following is the code that can save you time from search on the web- "How to find all the required fields of an SObject in Apex?"

public class DynamicApex {
    public FieldWrapper getFields(String objName) {
        try {
            FieldWrapper wr = new FieldWrapper();
            for (Schema.SObjectField f : Schema.getGlobalDescribe().get(objName).getDescribe().fields.getMap().values()) {
                Schema.DescribeFieldResult r = f.getDescribe();
                if (!r.isNillable() && r.isCreateable() && !r.isDefaultedOnCreate()) {
                    wr.requiredFields.add(r.getName());
                } else {
                    wr.otherFields.add(r.getName());
                }
            }
            return wr;
        } catch (Exception e) {
            throw new TypeException(e.getMessage());
        }
    }

    public class FieldWrapper {
        public List<String> requiredFields;
        public List<String> otherFields;

        FieldWrapper() {
            this.requiredFields = new List<String>();
            this.otherFields = new List<String>();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)