Sub topic 12
Working with Approvals in Apex
This chapter assumes you can read and write basic Apex and SOQL. It also assumes you have an approval process already built in Setup, as covered in earlier chapters: entry criteria, steps, approvers, and actions. Apex does not define approval processes. It submits records to them, responds to their requests, and reads their results.
What Apex can and cannot do
The Approval API runs processes that already exist. You cannot create steps or change approvers from code, because those are metadata. You can do the following:
- Submit a record to a process.
- Approve, reject, or recall a pending request.
- Lock, unlock, and check the lock state of a record.
- Reassign a pending request.
- Query the history through the ProcessInstance family of objects.
| Class or object | Purpose |
|---|---|
| `Approval.ProcessSubmitRequest` | Submits one record to an approval process |
| `Approval.ProcessWorkitemRequest` | Approves, rejects, or recalls one pending request |
| `Approval.ProcessResult` | Returned by `Approval.process`, with success flag, instance status, and new work item IDs |
| `ProcessInstance` | One run of a process for a record |
| `ProcessInstanceStep` | One completed action in a run |
| `ProcessInstanceWorkitem` | One pending request assigned to an approver |
Submitting a record
A submit request needs the record ID. Everything else is optional.
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());Other setters you will use:
setProcessDefinitionNameOrIdpicks a process by developer name. Without it, Salesforce evaluates the processes for the object in order of their process order and uses the first one whose entry criteria the record meets.setSubmitterIdsubmits on behalf of another user. That user must be an allowed initial submitter.setNextApproverIdsnames the approver when the step is set to let the submitter choose. The process must be configured that way.setSkipEntryCriteria(true)bypasses the entry criteria check. Use it sparingly, because it lets records into a process that was designed to exclude them.
The call runs as the current user, and the usual rules apply. The submitter must be allowed to submit. The record must not already be in an approval. The record must meet the entry criteria. If no process applies, you get an error with the status code NO_APPLICABLE_PROCESS.
Reading the result
ProcessResult gives you what you need to continue:
isSuccess()says whether the submission worked.getInstanceStatus()returnsPendingfor a request still waiting. It can returnApprovedright away if the process has no steps that need a person, for example when a step auto-approves.getInstanceId()is theProcessInstanceID.getNewWorkitemIds()lists the newProcessInstanceWorkitemIDs. You can use these directly to respond.getErrors()listsDatabase.Errorobjects when you use partial success.
Bulk submission
Approval.process accepts a list. Treat it like DML: call it once with many requests, never inside a loop. Pass false as the second argument to let valid requests succeed when others fail.
List<Approval.ProcessRequest> requests = new List<Approval.ProcessRequest>();
for (Id oppId : opportunityIds) {
Approval.ProcessSubmitRequest r = new Approval.ProcessSubmitRequest();
r.setObjectId(oppId);
r.setComments('Bulk submission');
requests.add(r);
}
List<Approval.ProcessResult> results = Approval.process(requests, false);
for (Integer i = 0; i < results.size(); i++) {
if (!results[i].isSuccess()) {
for (Database.Error e : results[i].getErrors()) {
System.debug(opportunityIds[i] + ' failed: ' + e.getStatusCode() + ' ' + e.getMessage());
}
}
}This assumes opportunityIds is a List<Id>, so the index in the results matches the index of the input. Results come back in request order.
Responding to a work item
A pending request is a ProcessInstanceWorkitem. To act on it, you need its ID. Either take it from getNewWorkitemIds() right after submission, or query it.
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 setAction values are Approve, Reject, and Removed. Removed recalls the request. It succeeds only if the running user may recall: the original submitter when the process allows it, or an administrator.
Two details matter in practice:
- The running user must be an assigned approver for that work item, or an administrator. Otherwise the call fails. In a multi-step process, one approval may only advance the instance to the next step. The result then still reads
Pending, and a new work item exists for the next approver. - For a step with several approvers, the step rules decide what one response does. Under "unanimous", the instance stays pending until everyone approves. Under "first response", the first answer decides the step.
You can also set setNextApproverIds on a work item request when the next step lets the approver choose.
Locking from code
Approval locking is automatic, but the API also exposes it: Approval.isLocked(recordId), Approval.lock(recordId), and Approval.unlock(recordId). Each has overloads that accept lists. Use isLocked before trying to update a record from automation, so you can skip or defer locked records instead of failing with a lock error. Unlocking a record in the middle of a pending approval is rarely correct. It lets users edit data that approvers are reviewing.
Reading approval history
The data model has one ProcessInstance per run and one ProcessInstanceStep per action taken. A subquery on the Steps relationship returns both at once.
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);
}
}StepStatus values include Started, Approved, Rejected, Removed, and Reassigned. The first step of a run has the status Started, and it records the submission.
Keep these points in mind:
- A record can have several
ProcessInstancerows over time. A rejection or recall ends one run, and a resubmission creates a new one. Order byCreatedDateand decide whether you want the latest or all of them. ProcessInstanceWorkitemholds only pending items. When someone responds, the work item is closed and a step is written.- The
Stepsrelationship covers completed actions. To list who still has to approve, queryProcessInstanceWorkitemwithActor.NameandActorId. - Sharing applies. Users see history only for records they can see.
Reassigning a pending request
You reassign by updating ActorId on the work item. Reassignment through DML is allowed for administrators and for users with the right permission on the process. It does not use Approval.process.
ProcessInstanceWorkitem item = [
SELECT Id, ActorId
FROM ProcessInstanceWorkitem
WHERE ProcessInstance.TargetObjectId = :opportunityId
AND ProcessInstance.Status = 'Pending'
LIMIT 1
];
item.ActorId = newApproverId;
update item;Testing approval code
Test classes can submit and approve records because approval process definitions are metadata that tests can see. The test cannot create the process, so it depends on the process existing in the org. Name it explicitly with setProcessDefinitionNameOrId so the test does not pick up some other process.
This example assumes an Opportunity process named Discount_Approval whose entry criteria are met by an Amount above 100000, and whose first step is assigned to the submitter's manager or to the running user.
@IsTest
private class DiscountApprovalTest {
@IsTest
static void submitAndApprove() {
Opportunity opp = new Opportunity(
Name = 'Big deal',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
Amount = 250000
);
insert opp;
Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
req.setObjectId(opp.Id);
req.setProcessDefinitionNameOrId('Discount_Approval');
Approval.ProcessResult submitted = Approval.process(req);
System.assert(submitted.isSuccess(), 'Submission should succeed');
System.assertEquals('Pending', submitted.getInstanceStatus());
System.assert(Approval.isLocked(opp.Id), 'Record should be locked');
Approval.ProcessWorkitemRequest wi = new Approval.ProcessWorkitemRequest();
wi.setWorkitemId(submitted.getNewWorkitemIds()[0]);
wi.setAction('Approve');
Approval.ProcessResult approved = Approval.process(wi);
System.assertEquals('Approved', approved.getInstanceStatus());
System.assert(!Approval.isLocked(opp.Id), 'Record should be unlocked');
}
}If the approver is a different user, wrap the second half in System.runAs(approverUser). Email alerts sent by approval actions do not leave the test, but they count toward email limits when they run. Also test the negative path: a record that fails the entry criteria should produce an error, not a silent skip.
Common errors
| Error status code | Usual cause |
|---|---|
| `NO_APPLICABLE_PROCESS` | The record fails entry criteria, or the submitter is not an allowed initial submitter |
| `ALREADY_IN_PROCESS` | The record has a pending approval |
| `MANAGER_NOT_DEFINED` | The step uses the submitter's manager and none is set |
| `INVALID_OPERATION` | The user is not an assigned approver on the work item |
| `ENTITY_IS_LOCKED` | An update ran against a record locked by a pending approval |
Design considerations
Prefer a work item ID from getNewWorkitemIds() over a query when you have it. It is cheaper and unambiguous. Keep approval calls out of loops. Decide which user the code should run as, since the submitter, approver, and comments all follow from that. Finally, keep logic that belongs in the process, such as who approves and what happens on rejection, in the process definition. Apex should trigger it, not duplicate it.
Exercise
A trigger on Opportunity submits records to approval. In a bulk update of 200 records, 20 of them do not meet the entry criteria. How should you call the API so the other 180 are still submitted, and how do you find out which ones failed?
Show answer
Build a List<Approval.ProcessRequest> with one ProcessSubmitRequest per record and call Approval.process(requests, false) once. The false argument allows partial success. Loop over the returned List<ProcessResult> in order and, for each result where isSuccess() is false, read getErrors() (for example NOAPPLICABLEPROCESS) and map it back to the record at the same index.
Exercise
After a rejection, a user resubmits the same record. A report of "current approval status" built from ProcessInstance shows two rows for the record. Which row should you read, and how do you select it in SOQL?
Show answer
Read the most recent run. Each submission creates a new ProcessInstance, so filter on TargetObjectId and use ORDER BY CreatedDate DESC LIMIT 1. The older instance remains as history with the status Rejected.