function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Yao LinYao Lin 

How to unlock a record right after submitted in an Approval Process?

Hi,

I need to unlock a record after it is submitted in an Approval Process for a custom object Sales Order. I tried Apex trigger, but it seems not working. Will I need an Apex Test for the trigger? If so, how can I write it? Please help!

​​​​​​
Trigger SOLockRecord on PBSI__PBSI_Sales_Order__c (after update) {

For (PBSI__PBSI_Sales_Order__c so: Trigger.New){
if(Approval.isLocked(so.Id)){
Approval.unlock(so.Id);
}}
    
}

 
VinayVinay (Salesforce Developers) 
Hi,

Did you try in Final approval action, make this record as unlock for editing?

Below link has working example to Lock/Unlock record thorough Apex code 

http://salesforceworld4u.blogspot.com/2017/07/how-to-lockunlock-record-thorough-apex.html

Hope above information was helpful.

Please mark as Best Answer so that it can help others in the future.

Thanks,
Vinay Kumar
Yao LinYao Lin
Hi Vinay, 

I need to unlock the record immediatly after users submit it for approval. 
Yes, I tried the Apex Code too. It didn't work either. I don't know how to write the Apex Test code. 
public class UnlockSOApprovalProcess{
   public static void ListSO(){
   
//Get records to unlock
List<PBSI__PBSI_Sales_Order__c> soList = new List<PBSI__PBSI_Sales_Order__c>();
//Check locked records
List<PBSI__PBSI_Sales_Order__c> soLockList = new List<PBSI__PBSI_Sales_Order__c>();
for(PBSI__PBSI_Sales_Order__c so :soList){
    if(Approval.isLocked(so.id)){
        soLockList.add(so);
    }
}
//Unlock record
if(!soLockList.isEmpty()){
    //Unlock records
    List<Approval.UnlockResult> ulrList = Approval.unlock(soLockList, 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 Sales Order 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('Sales Order fields that affected this error: ' + err.getFields());
            }
        }
    }
}
}
}