How to get Salesforce object records with only required fields in Apex

|
| By Webner

Problem:

If you want to get records with dynamic fields (all fields or only required fields) selection of an object in Salesforce.

Solution:

List normalFields = new List();
List requiredFields = new List();
Schema.DescribeSObjectResult objectDetails =
ObjectName.sObjectType.getDescribe();
Map fieldsMap = objectDetails.fields.getMap();
for(String fieldName : fieldsMap.keySet()) {
Schema.SObjectField objectField = fieldsMap.get(fieldName);
Schema.DescribeFieldResult objectFieldDetails = objectField.getDescribe();
Boolean isNillable = objectFieldDetails.isNillable();
if (isNillable) {
normalFields.add(fieldName);
} else {
if (copyPolicyCustomFields) {
requiredFields.add(fieldName);
}
}
}
// Here we are creating dynamic SOQL with object required fields only
String requiredFieldsStr = string.join(requiredFields,',');
String queryString = 'select ' + requiredFieldsStr + ' from obectName';
// Here we are creating dynamic SOQL with not required fields
String normalFieldsStr = string.join(normalFields,',');
String queryString = 'select ' + normalFieldsStr + ' from obectName';
result = database.query(queryString);

Leave a Reply

Your email address will not be published. Required fields are marked *