[SalesForce] APEX Lock and Unlock a Record

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);


 }

Best Answer

== 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){
Related Topic