By using Apex, we can lock/unlock records without using any approval process. Before writing
any code in apex, first of all we need to go to setup -> Automation Process Setting-> check
Enable record locking and unlocking in Apex.
Below is the code snippet for to lock records directly from Apex class:
customObj__c [] recordList = [SELECT Id from customObj__c WHERE Name
LIKE ‘testName%’];
// to lock the records
Approval.LockResult[] lockedResultList = Approval.lock(recordList,false);
Here the lock method of Approval class takes 2 parameters:
• The set of records need to be locked.
• Boolean allorNothing, It returns the lock results, including failures if set to false. So it
supports partial locking.
To check which records successfully got locked as well as the failed records, we
can iterate overthe list of records below :-
// Iterate to check success & failure records
for(Approval.LockResult lr : lockedResultList) {
if (lr.isSuccess()) {
System.debug('Locked record id –> ' + lr.getId());
} else {
for(Database.Error err : lr.getErrors()) {
System.debug('error –> '+err.getStatusCode() +
': ' + err.getMessage());
}
}
}
customObj__c [] recordList = [SELECT Id from customObj__c WHERE Name
LIKE ‘testName%’];
// to unlock the records
Approval.UnlockResult[] urList = Approval.unlock(recordList,false);
To see more available features of Approval class, please refer to the link below: