I was writing a utility class which can give the names of the fields that changed during an update trigger (I have a specific set of fields that i want to track, not all fields). My code snippet is below.
My concern is, if the field is a text field, and it changes from empty string to null (or vice-versa), will this code detect it as a change? After writing my code, i tried using workbench to test it out, but its not helping. I took a record where a text field is null (got it through SOQL query). Then used Apex execute to update it to blank field (sampleRecord.fieldName__c = '';). But querying it again still shows the field as null. So i am unable to test my implementation.
public Map<Id,Set<String>> findFieldChanges(Map<Id,sObject> oldRecordsMap, Map<Id,sObject> newRecordsMap, Set<String> fieldsToBeTracked){
Map<Id,Set<String>> recIdToFieldNamesMap = new Map<Id,Set<String>>();
for(sObject currOldRecord : oldRecordsMap.values()){
sObject currNewRecord = newRecordsMap.get(currOldRecord.Id);
for(String currField : fieldsToBeTracked){
if(currOldRecord.get(currField) != currNewRecord.get(currField)){
if(!recIdToFieldNamesMap.containsKey(currOldRecord.Id)){
recIdToFieldNamesMap.put(currOldRecord.Id, new Set<String>());
}
(recIdToFieldNamesMap.get(currOldRecord.Id)).add(currField);
}
}
}
return recIdToFieldNamesMap;
}
The line
if(currOldRecord.get(currField) != currNewRecord.get(currField))
is what i am curious about. If it a text field, does it differentiate between null and blank?
after update
? If so, then my point still stands. There will never be an empty string in your fields. Further, if you're usingbefore update
for whatever reason, you will want to useafter update
instead, because triggers run in an indeterminate order, so you cannot guarantee you have the final state of the fields untilafter update
starts, because the records will be locked then.if(currOldRecord.get(currField) != currNewRecord.get(currField) && currNewRecord.get(currField) != '')
Just be aware that you're probably wasting CPU time for a situation that will never occur.