Sub topic 13
Reading approval history
This chapter assumes you can run SOQL in the Developer Console, know the approval objects from the data model chapter, and can submit a record for approval. It covers where approval history appears, how to query it, and how to read what you get back.
Where history lives
Every submission creates a ProcessInstance record. Each action on it creates a ProcessInstanceStep record. Each approval request that is still waiting creates a ProcessInstanceWorkitem record. Together these three objects are the approval history.
| Object | Holds | Lifetime |
|---|---|---|
| `ProcessInstance` | One run of a process on one record. Fields include `Status`, `TargetObjectId`, `CompletedDate`. | Permanent |
| `ProcessInstanceStep` | One completed event: submission, approval, rejection, reassignment, removal. | Permanent |
| `ProcessInstanceWorkitem` | One pending request assigned to one user or queue. | Deleted when the request is answered |
| `ProcessInstanceNode` | The approval step definition the instance passed through. | Permanent |
The lifetime column matters for history. A work item describes the present, so it disappears once someone responds. The step record that replaces it is what you read later.
The Approval History related list
The simplest way to read history is the Approval History related list on the record page. Users see it only if your admin added it to the page layout. In Lightning, add the related list to the layout, or place the Approval History component on a Lightning page.
The list shows each step with its date, status, assigned approver, actual approver, and comments. Two details are easy to misread:
- Assigned To is who the request was addressed to. Actual Approver is who responded. These differ when a delegated approver acts, an admin responds on someone's behalf, or a queue member picks up the request.
- While a request is pending, the list shows a pending row with Approve/Reject and Reassign links for users who may act. Those links go away once the request is answered.
Each submission adds a new block of rows. If a record was rejected and resubmitted, the earlier run stays in the list, and the newest run is at the top.
Reading status values
Most mistakes in history code come from mixing up the two status fields.
ProcessInstance.Status describes the whole run:
Pending: waiting on at least one approver.Approved: the final approval step was approved.Rejected: rejected, and the run is finished.Removed: recalled or removed before completion.Held: used by some process types. Treat it as not finished.
ProcessInstanceStep.StepStatus describes one event:
Started: the submission itself. This is the first step of every run.ApprovedandRejected: an approver's response.Reassigned: the request was handed to another approver.NoResponse: the step ended without that approver answering. This happens, for example, when a first-response step is completed by someone else.Removed: the request was recalled.
A single run with two approvers on a unanimous step produces one Started step and two Approved steps. The run's Status stays Pending until the last approver responds.
Querying a record's full history
This query reads each run for a record and the steps in it. Run it in anonymous Apex with a real record Id in opportunityId.
Id opportunityId = '006XXXXXXXXXXXXXXX'; // replace with a real Opportunity Id
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);
}
}Points to note:
- Filter on
TargetObjectId. The approval objects are meant to be queried in the context of a record, so unfiltered queries can be rejected or slow. Stepsis the child relationship name forProcessInstanceStep. It holds completed events only.Actoris the user who responded. For theStartedstep, it is the submitter.Commentsis null when the approver left none, so guard before calling string methods on it.
Steps and pending work together
Steps do not include requests that are still pending. To show a timeline with both, query the StepsAndWorkitems relationship. It exposes the read-only ProcessInstanceHistory object, which merges the two.
Id opportunityId = '006XXXXXXXXXXXXXXX'; // replace with a real Opportunity Id
for (ProcessInstance pi : [
SELECT Id, Status,
(SELECT StepStatus, Actor.Name, OriginalActor.Name, Comments, CreatedDate
FROM StepsAndWorkitems
ORDER BY CreatedDate DESC, Id DESC)
FROM ProcessInstance
WHERE TargetObjectId = :opportunityId
]) {
for (ProcessInstanceHistory h : pi.StepsAndWorkitems) {
String who = h.Actor.Name;
if (h.OriginalActorId != h.ActorId) {
who += ' (assigned to ' + h.OriginalActor.Name + ')';
}
System.debug(h.StepStatus + ' by ' + who + ' on ' + h.CreatedDate);
}
}OriginalActor is the person or queue the request was assigned to. Actor is who actually acted. Comparing them is how you reproduce the Assigned To and Actual Approver columns from the related list. ProcessInstanceHistory cannot be queried on its own, only through this relationship or ProcessSteps.
Answering common questions
Who is a record waiting on?
Pending work items answer this directly:
Id opportunityId = '006XXXXXXXXXXXXXXX'; // replace with a real Opportunity Id
for (ProcessInstanceWorkitem w : [
SELECT Actor.Name, CreatedDate
FROM ProcessInstanceWorkitem
WHERE ProcessInstance.TargetObjectId = :opportunityId
AND ProcessInstance.Status = 'Pending'
]) {
System.debug('Waiting on ' + w.Actor.Name + ' since ' + w.CreatedDate);
}Actor here may be a queue, so Actor.Name can be a queue name instead of a person.
Who approved the last time?
Querying for many records at once is the pattern to learn. This class returns the most recent approver for each record in a set, using one query.
public with sharing class ApprovalHistoryReader {
public static Map<Id, String> lastApprover(Set<Id> recordIds) {
Map<Id, String> result = new Map<Id, String>();
for (ProcessInstanceStep s : [
SELECT ProcessInstance.TargetObjectId, Actor.Name, CreatedDate
FROM ProcessInstanceStep
WHERE ProcessInstance.TargetObjectId IN :recordIds
AND StepStatus = 'Approved'
ORDER BY CreatedDate ASC
]) {
// Later rows overwrite earlier ones, so the newest approval wins.
result.put(s.ProcessInstance.TargetObjectId, s.Actor.Name);
}
return result;
}
}Run ApprovalHistoryReader.lastApprover(new Set<Id>{ opportunityId }) in anonymous Apex to try it. The query sits outside any loop over records, which keeps you inside the SOQL query limit in triggers and batch jobs.
How long did approval take?
Subtract the Started step's CreatedDate from the final step's, or use ProcessInstance.CompletedDate. ProcessInstanceStep also has ElapsedTimeInDays, ElapsedTimeInHours and ElapsedTimeInMinutes, which report the time since the previous step.
Reporting on approvals
Reports on approval data depend on which report types your org exposes. The usual options are:
- Add the Approval History related list to layouts and use it for single-record review.
- Ask an admin to create a custom report type if the standard types do not cover the approval objects in your org.
- For dashboards that need cycle time or per-approver counts, query the objects with SOQL and write results to a custom object, or use an analytics tool.
Check the report type list in your org before building anything. Availability has changed between releases.
Visibility and gotchas
- Visibility follows the record. Users generally see approval history only for records they can see. Code running
with sharingfollows the same rule, so a query in awith sharingclass can return fewer rows than a system-context test shows. - Deleting a record deletes its history. If the target record is deleted, its
ProcessInstancegoes with it. If you need an audit trail that outlasts the record, copy history to a custom object. - Recall adds a step; it does not erase. A recalled request appears as a
Removedstep, and the run'sStatusbecomesRemoved. - Comments are plain text. Approvers can type anything, so escape the value before putting it in a Visualforce page or other markup.
- Test data is thin. In a test class,
Approval.processcreates real history rows you can query. A test that only inserts a record has none.
Check your understanding
Exercise
A record was submitted, and a unanimous step with two approvers is half done. Which StepStatus values are on the run's steps, which objects show who is still pending, and what is the instance Status?
Show answer
The steps contain one Started step (the submission) and one Approved step (the approver who has responded). The remaining approver appears as a ProcessInstanceWorkitem, not as a step. The ProcessInstance.Status is Pending until the last approver responds.
Exercise
You need a list showing both completed responses and still-pending requests for one record, with the original assignee beside the actual approver. Which relationship do you query, and which two fields do you compare?
Show answer
Query the StepsAndWorkitems relationship on ProcessInstance, which returns ProcessInstanceHistory rows. Compare OriginalActor (who the request was assigned to) with Actor (who acted).
Exercise
A scheduled job reports "last approver" for 200 records, but it runs out of SOQL queries. What change fixes it?
Show answer
Move the query out of the per-record loop. Collect the record Ids into a set, query ProcessInstanceStep once with ProcessInstance.TargetObjectId IN :recordIds, and build a map from record Id to approver name, as in ApprovalHistoryReader.lastApprover.