Lock/unlock record using Apex in Salesforce
- December 05, 2022
Whenever we create an approval process, we get an option to Lock/Unlock records in the initial submission action, final approval and rejection action.
We can perform the same actions by using apex lock() and unlock() methods in the system approval namespace by passing in record IDs or sObjects.
Step 1: Enable record locking and unlocking in Apex
- Go to setup
- Search for Process Automation setting
- Check the checkbox for Enable record locking and unlocking in Apex
- Click Save
Step 2: Now you can use apex lock() and unlock() in your custom codes.
Example:
Requirement: Suppose you want to Lock the Account record as soon as the status is changed to Inactive.
This can be done in various ways. I have created an Invocable action and flow for the same.
a. Created below Class with Invocable Action
public class LockRecord {
@InvocableMethod (label='Lock Accounts')
public Static void LockAccounts(List<Id> listAccIds){
List<Account> listAccountsToLock= [Select Id, Name from Account where id =:listAccIds] ;
for (Account accountToLock : listAccountsToLock)
{
Approval.lock(accountToLock.id);
}
}
}
b. Created a record trigger flow to invoke this Action
Configured flow as below:
Added the Lock Account Action.
Saved and Activated the flow.
c. To test the automation, I changed the account status to Inactive on a test record, and the record got locked successfully. Now only the users with “Modify all data” or “Modify All on Account level” can edit this record.
— By Rishabh Dubey