Created
February 16, 2022 22:55
-
-
Save jongpie/7a5bedfa20281e1ae0c6df819f3b2193 to your computer and use it in GitHub Desktop.
Handle (some of) the annoyances of working with SObjects
This file contains hidden or 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
Account acct = [SELECT Id, Name, CreatedDate FROM Account LIMIT 1]; | |
Datetime fakeCreatedDate = System.now(); | |
List<Contact> contacts = [SELECT Id, LastName, AccountId FROM Contact LIMIT 5]; | |
acct = (Account) new SObjectAnnoyanceHelper(acct) | |
.setReadOnlyField(Schema.Account.CreatedDate, fakeCreatedDate) | |
.appendChildren(contacts, 'Contacts') | |
.getRecord(); | |
System.debug('The updated account: ' + acct); | |
System.debug('The new CreatedDate: ' + acct.CreatedDate); | |
System.debug('Number of children contacts: ' + acct.Contacts.size()); | |
for (Contact con : acct.Contacts) { | |
System.debug('A child contact: ' + con); | |
} |
This file contains hidden or 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
public without sharing class SObjectAnnoyanceHelper { | |
private SObject record; | |
public SObjectAnnoyanceHelper(SObject record) { | |
this.record = record; | |
} | |
public SObjectAnnoyanceHelper appendChildren(List<SObject> children, String relationshipName) { | |
// Credit to James Simone for this method! | |
String endOfObject = '}'; | |
String serializedParent = JSON.serialize(this.record).removeEnd(endOfObject); | |
JSONGenerator gen = JSON.createGenerator(false); | |
gen.writeStartObject(); | |
gen.writeNumberField('totalSize', children.size()); | |
gen.writeBooleanField('done', true); | |
gen.writeObjectField('records', children); | |
gen.writeEndObject(); | |
String childrenJson = '"' + relationshipName + '" : ' + gen.getAsString(); | |
serializedParent = serializedParent += ',' + childrenJson + endOfObject; | |
this.record = (SObject) JSON.deserialize(serializedParent, SObject.class); | |
return this; | |
} | |
public SObjectAnnoyanceHelper setReadOnlyField(Schema.SObjectField field, Object value) { | |
return this.setReadOnlyField(field.getDescribe().getName(), value); | |
} | |
public SObjectAnnoyanceHelper setReadOnlyField(String fieldName, Object value) { | |
Map<String, Object> untypedRecord = (Map<String, Object>) JSON.deserializeUntyped(JSON.serialize(record)); | |
untypedRecord.put(fieldName, value); | |
this.record = (SObject) JSON.deserialize(JSON.serialize(untypedRecord), SObject.class); | |
return this; | |
} | |
public SObject getRecord() { | |
return this.record; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment