0

I am trying to create a custom button on a Visualforce page which will invoke an Apex method. The goal of the button is for the user to click it to approve of any records that are waiting on their approval. The approval process has multiple steps and records are automatically submitted for approval on creation.

I know how to create a new approval process using Apex, but that's not what I need. If I try to start a new approval process I get an error saying that the record is already in an approval process.

The closest I got was this:

    Approval.ProcessSubmitRequest approvalRequest = new Approval.ProcessSubmitRequest();
    approvalRequest.setComments('Submitted for approval');
    approvalRequest.setObjectId(caseResult.id);
    Approval.ProcessResult approvalResult = Approval.process(approvalRequest);

This is the error I get:

Process failed. First exception on row 0; first error: ALREADY_IN_PROCESS, This record is currently in an approval process.

How can I just move the record to the next step of the currently running approval process?

0

2 Answers 2

1

The key is that you have to use the Process Workitem Request instead of working directly with the actual Approval Request. Something like this should work, though I did not take the time to test it so it may need some tweaks:

public class approveRecord{

    public Boolean handleApproval(sObject record){
        Id piw = [Select Id from ProcessInstanceWorkitem 
              where ProcessInstance.TargetObjectId = :record.id].id;


        Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
        req.setComments('Some comments if needed');
        req.setAction('Approve');


        req.setWorkitemId(piw);

        Approval.ProcessResult result = Approval.process(req);

        return result.isSuccess();
    }
}
1
  • Thank you, this was exactly what I was looking for!
    – EmptyStuff
    Jul 25, 2019 at 16:34
1

ProcessSubmitRequest is to submit a record for approval process. And for given instance one record can only be under one approval process. You are submitting for another process process even though you are submitting it to the same approval process, which is counted as one more instance. so use this

//This is the current in progress step of your approval process

Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
req.setComments('Approval comments');
ProcessInstanceWorkitem pItem = [Select Id from ProcessInstanceWorkitem 
 where ProcessInstance.TargetObjectId =: yourRecordId];
req.setWorkitemId(pItem.Id);
req.setAction('Approve');
req. setNextApproverIds(new Id[] {List of user ids});
Approval.ProcessResult result = Approval.process(req);
1
  • Thank you this is what I was missing.
    – EmptyStuff
    Jul 25, 2019 at 16:34

Not the answer you're looking for? Browse other questions tagged .