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>();
}
}
}
Top comments (0)