Problem:
If you want to get records with dynamic fields (all fields or only required fields) selection of an object in Salesforce.
Solution:
List
List
Schema.DescribeSObjectResult objectDetails =
ObjectName.sObjectType.getDescribe();
Map
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);