Sub topic 12
Working with approvals in Apex
This chapter shows how to submit records, respond to approval requests, and read approval history from Apex. It assumes you know how an approval process is built (entry criteria, steps, approvers, and record locking) and that you can write basic Apex and SOQL.
The approval API at a glance
Apex exposes approvals through the Approval class. Two request types cover most needs:
Approval.ProcessSubmitRequestsubmits a record to an approval process.Approval.ProcessWorkitemRequestapproves, rejects, or removes a pending request.
Both are passed to Approval.process(), which returns an Approval.ProcessResult.
Submitting a record
Set the record Id on the request. If more than one process could apply, name the one you want.
Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
req.setComments('Submitting discount request for approval.');
req.setObjectId(opportunityId);
// Optional: target a specific process by developer name or Id.
// req.setProcessDefinitionNameOrId('Discount_Approval');
Approval.ProcessResult result = Approval.process(req);
System.debug('Submitted: ' + result.isSuccess() + ', status: ' + result.getInstanceStatus());The record must meet the entry criteria, and the running user must be an allowed initial submitter. Otherwise the call throws a DmlException, for example with NO_APPLICABLE_PROCESS. If you do not set a process, Salesforce uses the first process whose entry criteria the record meets, in process order.
Approving or rejecting a work item
Each pending approval request is a ProcessInstanceWorkitem. Query it for the target record, then respond.
ProcessInstanceWorkitem item = [
SELECT Id
FROM ProcessInstanceWorkitem
WHERE ProcessInstance.TargetObjectId = :opportunityId
AND ProcessInstance.Status = 'Pending'
LIMIT 1
];
Approval.ProcessWorkitemRequest wi = new Approval.ProcessWorkitemRequest();
wi.setWorkitemId(item.Id);
wi.setAction('Approve'); // or 'Reject'
wi.setComments('Approved by finance.');
Approval.ProcessResult result = Approval.process(wi);The action string is Approve, Reject, or Removed (a recall). The running user must be an assigned approver, a delegated approver, or an administrator. The call fails for anyone else.
If the step has several approvers, the work item you respond to is the one assigned to a particular user. A unanimous step stays pending until every approver has responded.
Reading approval history
Approval history lives in ProcessInstance (one per submission) and its child ProcessInstanceStep records (one per action taken). This query reads both.
List<ProcessInstance> instances = [
SELECT Id, Status, CompletedDate,
(SELECT StepStatus, Actor.Name, Comments, CreatedDate
FROM Steps
ORDER BY CreatedDate)
FROM ProcessInstance
WHERE TargetObjectId = :opportunityId
ORDER BY CreatedDate DESC
];
for (ProcessInstance pi : instances) {
for (ProcessInstanceStep s : pi.Steps) {
System.debug(s.Actor.Name + ': ' + s.StepStatus + ' - ' + s.Comments);
}
}Common errors
| Symptom | Likely cause |
|---|---|
| `NO_APPLICABLE_PROCESS` | The record does not meet any entry criteria, or the user is not an allowed submitter. |
| `ALREADY_IN_PROCESS` | The record already has a pending approval. |
| Query returns no work item | The request is already complete, or the filter did not match the record. |
| Update fails with a lock error | The record is locked while approval is pending. |
In tests, create the record, submit it, and query the work item. Approval work items exist in test context, so you can approve in the same test. Run the code as a user who is an approver, using System.runAs().
Exercise
A record is waiting on a step with two approvers, and the step requires unanimous approval. One approver approves with Approval.process(). What is the instance status afterward, and why?
Show answer
The instance stays Pending. A unanimous step completes only when every assigned approver has approved, so the work item for the second approver remains open and the record stays locked.
Exercise
Which objects do you query to list who acted on an approval and what comments they left?
Show answer
Query ProcessInstance for the submission and its child Steps (ProcessInstanceStep) for each action, including Actor.Name, StepStatus, and Comments.