Unit of Work : Updating Records in Salesforce Using UOW

Updating Records in Salesforce Using Unit of Work

The following example demonstrates how to update an existing Salesforce record using the Unit of Work pattern from the FinancialForce Apex Common Library. This approach ensures efficient transaction management and follows best practices for enterprise applications.

Code Example


public with sharing class ExampleService {
    /**
     * Updates an existing Object_A__c record with a new value for field2.
     * 
     * @param recordId The ID of the record to update.
     * @param newValue The new value for field2.
     */
    public void updateRecord(Id recordId, String newValue) {
        // Create a Unit of Work instance
        fflib_SObjectUnitOfWork uow = new fflib_SObjectUnitOfWork(
    new Schema.SObjectType[] {
        Object_A__c.SObjectType
    }
);
        
        // Query the existing record
        Object_A__c objA = [SELECT Id, field2 FROM Object_A__c WHERE Id = :recordId];
        
        // Modify the field
        objA.field2 = newValue;
        
        // Register the record as dirty
        uow.registerDirty(objA);
        
        // Commit the changes
        uow.commitWork();
    }
}

Explanation

  • Query the Record: The existing record is fetched from the database using SOQL, ensuring we have the record's current data before making changes.
  • Modify the Field: The field you want to update (in this case, field2) is assigned a new value.
  • Register as Dirty: The record is marked as "dirty" using uow.registerDirty, which tells the Unit of Work to include this update during its commit operation.
  • Commit the Changes: Finally, uow.commitWork applies all pending changes to the database in a single transaction.
Unit of Work : Updating Records in Salesforce Using UOW Unit of Work : Updating Records in Salesforce Using UOW Reviewed by dasfrogpractice on 04:33 Rating: 5

No comments:

Theme images by mariusFM77. Powered by Blogger.
Youtube Channel Image
Dasfrog Subscribe To watch more Salesforce Training
Subscribe