[SalesForce] Recall approval process by apex

I am attempting to recall an approval process with the following Apex code:

Approval.ProcessWorkitemRequest pwr = new
Approval.ProcessWorkitemRequest();  pwr.setAction('Removed');
pwr.setWorkItemId(workItems[0].id);
Approval.ProcessResult result = Approval.process(pwr);

It works fine when I run it as an administrator or when the user running it is the submitter of the approval process.

But it doesn't work for any other users; I get this error:

Process failed. First exception on row 0; first error: INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY, insufficient access rights on cross-reference id

How can I make this work for any user?

To complete my question, I created a visualforce page to add a custom button on the object page layout calling the apex method below ManageButton.documentCustomGetApprovalProcess

public without sharing class ManageButton 
{
    // Constructor
    public ManageButton(ApexPages.StandardController stdController) 
    {
    }

    /**
     * method used by the Get Approval Process button
     */   
    public PageReference documentCustomGetApprovalProcess()
    { 
        string docId = ApexPages.currentPage().getParameters().get('id');

        ProcessInstanceWorkitem[] workItems = [
             SELECT Id
               FROM ProcessInstanceWorkitem 
              WHERE ProcessInstance.TargetObjectId = :docId
                AND ProcessInstance.Status = 'Pending'];

        Approval.ProcessWorkitemRequest pwr = new Approval.ProcessWorkitemRequest();
        pwr.setAction('Removed');
        pwr.setWorkItemId(workItems[0].id);
        Approval.ProcessResult result = Approval.process(pwr);

        // Redirect the user back to the original page
        PageReference pageRef = new PageReference('/' + docId);
        pageRef.setRedirect(true);
        return pageRef;
    }
}

Even specifing "without sharing" on the class I have the error I mentioned.

Best Answer

By design, Approval Processes only allow either a System Administrator and/or the Initial Submitter to recall the submission.

Per Salesforce documentation:

enter image description here

However, to answer your question How can I make this work for any user? you will need your Apex code to change the context user to be a System Administrator.

One way to achieve this is by using Apex Email Service and sending an email to its service address from your Apex code. Email Services let you specify a context user that the code will run under and so in that apex code you can try performing your recall action.

Side note, I've used this Apex Email Service technique to run code as a specific user in other projects like Salesforce Chatter Bot for Feeds.

enter image description here

Related Topic