How to check if a specific Account record has mandatory fields that are empty? What could be the steps of doing it?
This is what I was trying to do (but with no luck):
//All field names of the Account object
static Set<String> accountFieldSet = Schema.SObjectType.Account.fields.getMap().keySet();
//Map of Account fields
static Map<String, Schema.SObjectField> accountFieldMap = Schema.SObjectType.Account.fields.getMap();
Here's the method for getting all the mandatory fields:
public static Set<String> getMandatoryFields(){
Set<String> mandatoryFields = new Set<String>();
for(String fieldName : accountFieldSet){
Schema.SObjectField field = accountFieldMap.get(fieldName);
Schema.DescribeFieldResult describeFieldResult = field.getDescribe();
Boolean isFieldMandatory = !describeFieldResult.isNillable();
if (isFieldMandatory){
mandatoryFields.add(fieldName);
}
}
return mandatoryFields;
}
Here's the method for getting all the Account records that have empty mandatory fields:
public static List<Account> getAccountsToUpdate(List<Account> updateAccounts, Set<String> mandatoryFields){
List<Account> accountsToUpdate = new List<Account>();
List<String> accountFieldList = new List<String>();
accountFieldList.addAll(accountFieldSet);
for (Account a : updateAccounts){
for (String fieldName : accountFieldList){
if (mandatoryFields.contains(fieldName)){
if (a.get(fieldName) == null){
accountsToUpdate.add(a);
}
}
}
}
return accountsToUpdate;
}
And here's the the code execution portion:
try {
update updateAccounts;
} catch (System.DmlException ex) {
if (ex.getDmlType(0) == StatusCode.REQUIRED_FIELD_MISSING){
Set<String> mandatoryFields = AccountBILevelCalc.getMandatoryFields();
AccountBILevelCalc.getAccountsToUpdate(updateAccounts, mandatoryFields);
//not finished
}
}
The problem that I face is that accountFieldSet
also holds the fields that don't exist on the form from which the account was created. That's why the list of mandatory fields also holds the fields that I don't care about.