Skip to content

Instantly share code, notes, and snippets.

@brianmfear
Last active April 17, 2020 09:10
Show Gist options
  • Save brianmfear/b147b7eca2ff7bb2736635cd3bef4e17 to your computer and use it in GitHub Desktop.
Save brianmfear/b147b7eca2ff7bb2736635cd3bef4e17 to your computer and use it in GitHub Desktop.
Updating only changed fields in a standard controller
public class UpdateChangedFieldsController {
SObject oldRecord, currentRecord;
public UpdateChangedFieldsController(ApexPages.StandardController controller) {
oldRecord = controller.getRecord().clone();
currentRecord = controller.getRecord();
}
public PageReference saveChanges() {
SObject newClone = currentRecord.getSObjectType().newSObject(currentRecord.Id);
Map<String, Object>
oldValues = oldRecord.getPopulatedFieldsAsMap(),
newValues = currentRecord.getPopulatedFieldsAsMap();
for(String key: newValues.keySet()) {
if(newValues.get(key) != oldValues.get(key)) {
newClone.put(key, newValues.get(key));
}
}
try {
upsert newClone;
return new ApexPages.StandardController(newClone).view();
} catch(Exception e) {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment