Set Approval Process Lock And Unlock Records Using Apex Code
Sometimes we have faced business requirement to Lock or Unlock records in Salesforce. We can use apex lock()
and unlock()
methods in the System.Approval
namespace to lock and unlock records by passing in record IDs or sObjects.
To enable this feature, go to Setup | Search Automation Settings in the Quick Find box | click on Automation Settings. Then, select Enable record locking and unlocking in Apex.
Lock Record Example:
//Get records to lock List<case> caseList = [SELECT Id From Case LIMIT 10]; //Lock records List<Approval.LockResult> lrList = Approval.lock(caseList, 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('Case fields that affected this error: ' + err.getFields()); } } }
Unlock Record Example:
//Get records to unlock List<case> caseList = [SELECT Id From Case LIMIT 10]; //Check locked records List<case> caseLockList = new List<Case>(); for(Case c :caseList){ if(Approval.isLocked(c.id)){ caseLockList.add(c); } } //Unlock record if(!caseLockList.isEmpty()){ //Unlock records List<Approval.UnlockResult> ulrList = Approval.unlock(caseLockList, false); // Iterate through each returned result for(Approval.UnlockResult ulr : ulrList) { if (ulr.isSuccess()) { //Operation was successful, so get the ID of the record that was processed System.debug('Successfully locked account with ID: ' + ulr.getId()); } else { //Operation failed, so get all errors for(Database.Error err : ulr.getErrors()) { System.debug('The following error has occurred.'); System.debug(err.getStatusCode() + ': ' + err.getMessage()); System.debug('Case fields that affected this error: ' + err.getFields()); } } } }