How to check if a record is locked or not in Apex during an approval process

This came out in Winter16. It's part of the approval class

Approval.isLocked(recordId)

This method can also accept List<Id>, SObject, or List<SObject>.

You can also now lock and unlock them from Apex. See the documentation on the Approval class.


I believe it's possible to query for the existence of an Approval Request related to your record, I believe this is via: ProcessInstance. Try checking out:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_process_example.htm

Additionally, you could write a method to attempt to update the record, and trap the exception message that comes from the record being locked and hide the buttons based on that result!


The IsLocked field is not currently exposed via the API or SOQL, but there's an idea on the IdeaExchange to add that functionality.

In the meantime, you can work around that by created a custom field on the object called In_Approval_Process__c, and edit your approval process to set this field when the record is submitted for approval and clear it after approval is complete.

You can't totally hide or disable the buttons, but you can prevent them from doing anything. Switch the button's Content Source from URL to Execute Javascript and do something like the following:

var linkUrl = '/whatever/your/button/url/would/have/been';
var isLocked = {!sObject.In_Approval_Process__c};
if (isLocked) {
  alert('This record is locked for approval.  Please try again after it has been accepted.');
} else {
  window.location.href = linkUrl;
}