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

Author - Webner
28.10.2020
|
0 Comments
||

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);

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

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