I wanted to lock and unlock records based on a check box. I know that you can do this stuff via a validation rule but I think that is difficult to maintain if adding fields. I wrote an apex trigger using Approval.Lock. I am able to Lock the record however I am unable to grammatically unlock the records. Once the record is locked if I uncheck my ISLock before update it treats it as True. IF I use After Update the record is read only even though I am making it unlocked. Below is my code.

 Trigger AccountLockRecord on Account (before insert, after update) {

     List<Account> lstUnLockAccount = new List<Account>();
     List<Account> lstLockAccount = new List<Account>();

For (Account soAccount: Trigger.New){


    If (soAccount.ISLock__c = True){
        system.debug(logginglevel.debug, 'DEBUG: lOCK' );
         lstLockAccount.add(soAccount);

       // Approval.LockResult[] lrList = Approval.lock(lstAccount, false);

    } else If (soAccount.ISLock__c = False){

        system.debug(logginglevel.debug, 'DEBUG: uNlOCK' );
          lstUnLockAccount.add(soAccount);

      //  Approval.UnlockResult[] lrList1 = Approval.unlock(lstAccount);

    }         
   }

        Approval.LockResult[] lrList1 = Approval.lock(lstLockAccount, false);
        Approval.LockResult[] lrList2 = Approval.lock(lstUnLockAccount, false);


 }
  • 1
    lock & unlock are treated as DMLs so you can't do these inside a for loop – Jarvis Aug 21 at 13:35
  • Ok, fine. I did it outside of the for loop and that still gives same issue. I edited the code above – Brooke Aug 21 at 13:44
up vote 9 down vote accepted

== is for equality checks, = is for assignment. As such:

If (soAccount.ISLock__c = True){

will assign the value of true to IsLock__c, and this statement will always be true. For this reason, I always recommend that you avoid comparing to true/false values, because it can prevent typos like this from compiling.

If (soAccount.IsLock__c){

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.