Skip to content

Instantly share code, notes, and snippets.

@brianmfear
Last active April 17, 2020 09:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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