Sub topic 11
Where approval data is stored
This chapter covers the objects Salesforce uses to record approval activity. It assumes you know SOQL basics, how relationships and child subqueries work, and the approval process building blocks from earlier chapters: steps, approvers, and submission. The Apex code in the later chapters builds on this data model.
Why the data model matters
Setup shows an approval process as a configuration. At run time, each submission creates data. That data lets you:
- Find out whether a record is waiting for approval.
- Find out who has to act.
- Report on who approved or rejected something, and when.
- Respond to a request from code.
Three standard objects hold this data: ProcessInstance, ProcessInstanceStep, and ProcessInstanceWorkitem. A fourth, ProcessInstanceNode, describes the steps a particular instance passes through. Each approval has its own set of these records, separate from your record's own fields.
The three main objects
| Object | What one row represents | Lifetime |
|---|---|---|
| `ProcessInstance` | One submission of one record to one approval process | Permanent history |
| `ProcessInstanceStep` | One completed action in that submission (submit, approve, reject, recall, reassign) | Permanent history |
| `ProcessInstanceWorkitem` | One pending request waiting for one approver | Exists only while the request is pending |
The key distinction is between history and pending work. Steps are history. Workitems are the to-do list. When an approver responds, the workitem is deleted and a step is created.
ProcessInstance
A ProcessInstance is created each time a record is submitted. If the same record is submitted, rejected, edited, and submitted again, it has two instances.
Fields you will use most often:
TargetObjectId: the Id of the record that was submitted, such as an opportunity.Status:Pending,Approved,Rejected, orRemoved.Removedmeans the request was recalled.ProcessDefinitionId: the approval process that was used.CompletedDate: when the instance finished. It is null while the instance is pending.LastActorId: the user who took the most recent action.SubmittedById: the user who submitted the record.
Started can also appear as a status when an instance has been created but not yet moved on. Treat Pending as the status that means "waiting for someone."
ProcessInstanceStep
A ProcessInstanceStep is one entry in the approval history. It is a child of ProcessInstance, and the relationship name used in subqueries is Steps.
Useful fields:
StepStatus: values includeStarted,Approved,Rejected,Removed,Reassigned, andNoResponse.ActorIdandActor: the user who acted.OriginalActorId: the user the request was first assigned to. It differs fromActorIdwhen a delegated approver or an administrator acted on someone else's behalf.Comments: the text the user entered.CreatedDate: when the action happened.
The first step for any submission has the status Started. It records the submission itself, with the submitter as the actor.
ProcessInstanceWorkitem
A ProcessInstanceWorkitem is one pending approval request assigned to one user. It is also a child of ProcessInstance, and the relationship name is Workitems.
Useful fields:
ProcessInstanceId: the parent instance.ActorId: the user who is currently expected to respond.OriginalActorId: the user the request was first assigned to.CreatedDate: when the request was assigned, which is useful for finding stale requests.
When the approver is a queue, the ActorId is the queue's Id, not a person's. When several approvers are assigned and the step requires a response from all of them, there is one workitem for each approver.
How the objects relate
The TargetObjectId field is a polymorphic lookup. It can point to any object that supports approvals. That is why you filter on the Id value rather than joining to a specific object type.
What happens to the data during an approval
Follow one submission through its life:
For a multi-step process, the platform creates a new workitem for the next step's approver after each approval. The instance stays Pending until the last step finishes.
Rejection and recall follow the same pattern:
- On rejection, the workitem is deleted, a
Rejectedstep is added, and the instance becomesRejected. - On recall, the workitem is deleted, a
Removedstep is added, and the instance becomesRemoved.
Querying the data
Is a record pending approval?
Query the instance, not the workitem. This works whether or not you have permission to see the workitem rows.
Id recordId = '006000000000001AAA'; // replace with a real record Id
Boolean isPending = ![
SELECT Id
FROM ProcessInstance
WHERE TargetObjectId = :recordId
AND Status = 'Pending'
LIMIT 1
].isEmpty();
System.debug('Pending approval: ' + isPending);Who has to act now?
Query workitems for the pending instance. Because ActorId can be a user or a queue, select the Id and check its type before treating it as a user.
Id recordId = '006000000000001AAA'; // replace with a real record Id
for (ProcessInstanceWorkitem w : [
SELECT Id, ActorId, OriginalActorId, CreatedDate
FROM ProcessInstanceWorkitem
WHERE ProcessInstance.TargetObjectId = :recordId
]) {
String kind = w.ActorId.getSObjectType() == User.SObjectType ? 'User' : 'Group/Queue';
System.debug(kind + ' ' + w.ActorId + ' since ' + w.CreatedDate);
}What happened so far?
Use a child subquery on Steps. This is the same shape used for history reporting in a later chapter.
Id recordId = '006000000000001AAA'; // replace with a real record Id
for (ProcessInstance pi : [
SELECT Id, Status,
(SELECT StepStatus, Actor.Name, OriginalActor.Name, Comments, CreatedDate
FROM Steps
ORDER BY CreatedDate)
FROM ProcessInstance
WHERE TargetObjectId = :recordId
ORDER BY CreatedDate DESC
]) {
for (ProcessInstanceStep s : pi.Steps) {
System.debug(s.StepStatus + ' by ' + s.Actor.Name + ': ' + s.Comments);
}
}Edge cases and common errors
- Workitems disappear. Do not use workitems for history. After the request is answered, the row is gone. Use steps.
- Queue approvers. A workitem assigned to a queue has a queue Id in
ActorId. A query such asActor.Namemay not return what you expect for a queue. Check the Id prefix orgetSObjectType()first. - Multiple instances per record. A record that has been through several rounds has several
ProcessInstancerows. Always filter onStatusor order byCreatedDateinstead of assuming one row. - Mismatched actors.
ActorIdandOriginalActorIdcan differ because of reassignment or a delegated approver. Report on both if you need to know who the request was meant for. - Visibility. Users see approval rows only when they can see the target record, and some operations on these objects need the "View All Data" or "Modify All Data" permission. If a query returns nothing in a test and data exists, check sharing and permissions.
- Read-only data. You cannot insert or update
ProcessInstance,ProcessInstanceStep, orProcessInstanceWorkitemrows with DML. Use the Approval API (covered in the next chapter) to change state. - Tests. Test classes cannot see approval data created in your org unless the test submits its own record. Create the record in the test, submit it with
Approval.process, then query the objects.
Checking a rejected submission
Suppose a record was submitted, rejected, edited, and submitted again. The data would look like this:
| Instance | Instance status | Steps in order |
|---|---|---|
| First `ProcessInstance` | `Rejected` | `Started`, `Rejected` |
| Second `ProcessInstance` | `Pending` | `Started` |
Only the second instance has a workitem. Ordering instances by CreatedDate DESC puts the current submission first.
Exercise
A manager says the "Pending Approvals" report built on ProcessInstanceWorkitem shows no data for approvals completed last month, and asks you to fix it. What do you explain, and which object should the audit report use?
Show answer
Workitems exist only while a request is pending. They are deleted when the approver responds, so completed approvals never appear in them. An audit report should use ProcessInstanceStep, reached through ProcessInstance, because steps are kept as permanent history and include the actor, status, comments, and date for each action.
Exercise
You need code that checks whether an opportunity is currently waiting for approval. Which object do you query, which two fields do you filter on, and why should you avoid assuming only one row comes back?
Show answer
Query ProcessInstance, filtering on TargetObjectId equal to the opportunity Id and Status equal to 'Pending'. A record that has been submitted several times has several ProcessInstance rows, so the status filter and a LIMIT or ordering by CreatedDate are needed to pick the right one.