Using Database.UpsertResult in unit of work - Salesforce
<!-- Custom Helper Class for ObjectA and ObjectB -->
public class UpsertUnitOfWorkHelper implements fflib_SObjectUnitOfWork.IDoWork {
public Database.UpsertResult[] Results { get; private set; }
private List<SObject> m_records;
public UpsertUnitOfWorkHelper() {
m_records = new List<SObject>();
}
public void registerSObjectUpsert(SObject record) {
m_records.add(record);
}
public void doWork() {
Results = Database.upsert(m_records, false); // False for partial success
}
// Helper method to get error details
public List<String> getErrorDetails() {
List<String> errors = new List<String>();
for (Database.UpsertResult result : Results) {
if (!result.isSuccess()) {
for (Database.Error error : result.getErrors()) {
errors.add('Error in record ' + result.getId() + ': ' + error.getMessage());
}
}
}
return errors;
}
}
<!-- Using the Unit of Work for ObjectA and ObjectB -->
// Create Unit Of Work
fflib_SObjectUnitOfWork uow = new fflib_SObjectUnitOfWork(
new Schema.SObjectType[] {
ObjectA__c.SObjectType,
ObjectB__c.SObjectType
}
);
// Register custom work for ObjectA and ObjectB
UpsertUnitOfWorkHelper upsertWork = new UpsertUnitOfWorkHelper();
uow.registerWork(upsertWork);
// Prepare records for upsert
ObjectA__c objARecord = new ObjectA__c(Name = 'Test A', CustomField__c = 'Value A');
ObjectB__c objBRecord = new ObjectB__c(Name = 'Test B', LookupField__c = objARecord.Id);
// Register records with the helper
upsertWork.registerSObjectUpsert(objARecord);
upsertWork.registerSObjectUpsert(objBRecord);
// Commit work
uow.commitWork();
// Retrieve results
Database.UpsertResult[] results = upsertWork.Results;
// Check for errors
List<String> errors = upsertWork.getErrorDetails();
if (!errors.isEmpty()) {
System.debug('Upsert Errors: ' + errors);
} else {
System.debug('All records upserted successfully.');
}
Using Database.UpsertResult in unit of work - Salesforce
Reviewed by dasfrogpractice
on
01:30
Rating:
No comments: