SFDC Customization

Record Locking/Unlocking From Apex

In this blog i am going to explain how you can lock and unlock record from apex without using approval process.
This feature was introduced back in winter 16.
To use this feature first goto setup –> Automation process setting –> enable “Enable record locking and unlocking in Apex” option.

Now Below is the code which can be used to lock and unlock the record without setting approval process.

customObject__c [] custObj = [SELECT Id from customObject__c WHERE Name LIKE ‘Test%’];

Approval.LockResult[] lrList = Approval.lock(custObj, false); // Locking the record

The above method supports bulk locking and also partial locking ie let say we have 10 records in a list and out of which 5 got locked successfully and 5 failed still the process will not fail because it has partial locking feature as well.

You can iterate over list of result to see which records got failed like below :-

// Iterate to see success and failure
for(Approval.LockResult lr : lrList) {
if (lr.isSuccess()) {
System.debug(‘Locked record id –> ‘ + lr.getId());
}
else {
for(Database.Error err : lr.getErrors()) {
System.debug(‘error check –> ‘+err.getStatusCode() + ‘: ‘ + err.getMessage());
}
}
}

Similar to above process you can also unlock the locked record.

customObject__c [] custObj = [SELECT Id from customObject__c WHERE Name LIKE ‘Test%’];
Approval.UnlockResult[] lrList = Approval.unlock(custObj, false); // Unlocking the records

To see more available options you can refer below approval class provided by salesforce.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_approval.htm

Leave a Reply