Set Approval Process Locks and Unlocks with Apex Code

New lock() and unlock() methods in the System.Approval namespace let you lock records by passing in record IDs or sObjects. Previously, you could set approval-process locks and unlocks only through the Salesforce user interface.

To enable this feature, from Setup, enter Process Automation Settings in the Quick Find box, then click Process Automation Settings. Then, select Enable record locking and unlocking in Apex.

Salesforce admins can edit locked records. Depending on your approval process configuration settings, an assigned approver can also edit locked records. Locks and unlocks that are set programmatically use the same record editability settings as other approval-process locks and unlocks. Record locks and unlocks are treated as DML. They’re blocked before a callout, they count toward your DML limits, and if a failure occurs, they’re rolled back along with the rest of your transaction. To change this rollback behavior, use an allOrNone parameter.

The new Approval.LockResult and Approval.UnlockResult classes let you interact with the results of your programmatic record locks and unlocks.

Table of Contents


// Query the accounts to lock
Account[] accts = [SELECT Id from Account WHERE Name LIKE \'Acme%\'];
// Lock the accounts
Approval.LockResult[] lrList = Approval.lock(accts, false);

// Iterate through each returned result
for(Approval.LockResult lr : lrList) {
    if (lr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug(\'Successfully locked account with ID: \' + lr.getId());
    else {
        // Operation failed, so get all errors                
        for(Database.Error err : lr.getErrors()) {
            System.debug(\'The following error has occurred.\');                    
            System.debug(err.getStatusCode() + \': \' + err.getMessage());
            System.debug(\'Account fields that affected this error: \' + err.getFields());

Leave a Comment

Your email address will not be published. Required fields are marked *

Select Language »