Created
May 24, 2022 11:58
-
-
Save brianmfear/a141ea12be1bc17e80be783b39c06e21 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://salesforce.stackexchange.com/a/376822/2984 | |
// Efficiently checking if any fields from a list of fields have changed | |
public class DataUtils { | |
public class Change { | |
public String[] changedFields = new String[0]; | |
public sObject record1, record2; | |
Change(String[] changedFields, sObject record1, sObject record2) { | |
this.changedFields = changedFields; | |
this.record1 = record1; | |
this.record2 = record2; | |
} | |
} | |
// true if any fields requested have changed | |
public static Boolean hasFieldChanges(String[] fieldsToCheck, sObject firstRecord, sObject secondRecord) { | |
Map<String, Object> oldValues = firstRecord.getPopulatedFieldsAsMap(); | |
Map<String, Object> newValues = secondRecord.getPopulatedFieldsAsMap(); | |
oldValues.keySet().retainAll(fieldsToCheck); | |
newValues.keySet().retainAll(fieldsToCheck); | |
return oldValues != newValues; | |
} | |
// Convenience method for checking one record change, returns empty list of fields if no change. | |
// My preference is to avoid returning null values when possible, but the choice is yours. | |
public static Change findFieldChanges(String[] fieldsToCheck, sObject firstRecord, sObject secondRecord) { | |
Change[] results = findFieldChanges(fieldsToCheck, new sObject[] { firstRecord }, new sObject[] { secondRecord }); | |
if(results.size() > 0) { | |
return results[0]; | |
} | |
return new Change(new String[0], firstRecord, secondRecord); | |
} | |
// Returns a list of records that has at least one change, and the fields that changed | |
public static Change[] findChangedRecords(String[] fieldsToCheck, sObject[] firstRecordList, sObject[] secondRecordList) { | |
Change[] results = new Change[0]; | |
for(Integer index = 0, size = firstRecordList.size(); index < size; index++) { | |
sObject firstRecord = firstRecordList[index]; | |
sObject secondRecord = secondRecordList[index]; | |
Map<String, Object> oldValues = firstRecord.getPopulatedFieldsAsMap(); | |
Map<String, Object> newValues = secondRecord.getPopulatedFieldsAsMap(); | |
String[] changedFields = new String[0]; | |
for(String field: fields) { | |
if(oldValues.get(field) != newValues.get(field)) { | |
changedFields.add(field); | |
} | |
} | |
if(changedFields.size() > 0) { | |
results.add(new Change(changedFields, firstRecord, secondRecord)); | |
} | |
} | |
return results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment