I'm trying to create a generic utility method which takes a List of sObjects and a Map of fieldNames to fieldValues. I'd like to, for example, do the following:
List<Lead> leadList = [SELECT Id FROM Lead WHERE...];
Map<String,Object> fieldValueMap = new Map<String,Object>();
fieldValueMap.put('MailingCountry','United States');
fieldValueMap.put('Description','My New Description');
update UtilityClass.updaterMethod(leadList, fieldValueMap);
Here's what I've got so far. My challenge is that I don't want to have loops within loops (that's gotten me into CPU time limit issues before).
Challenge: Given that the Map is of indeterminate size, how would I dynamically set any number of field values within the sObject loop without an inner loop?
public static List<SObject> setFieldValue(List<SObject> sobjList, Map<String,Object> fieldNameValueMap, Boolean skipInvalid) {
List<SObject> updatedList = new List<SObject>();
for(SObject sobj : sobjList) {
try {
//Written as if I had a single fieldName/Value parameter...
sobj.put(fieldName, fieldValue); //This is what needs to be replaced
updatedList.add(sobj);
}
catch(Exception e) {
if(skipInvalid) {}
else {
String typeString = sobj.getSObjectType().getDescribe().name;
//Written as if I had a single fieldName/Value parameter...
throw new TypeException(typeString + ' does not have a field called ' + fieldName, e);
}
}
}
return updatedList;
}
public class TypeException extends Exception {}
Boolean Trap
.