Workflow Approval Objects in Salesforce
I had reason this past week to work with Approval Processes in Apex. I guess I had never thought about it too deeply, but I was surprised to learn that these objects are all second-class objects.
If you’re not familiar with the Approval Process architecture, there are five main objects:
- ProcessInstance represents an end-to-end approval process;
- ProcessInstanceWorkItem represents a user’s pending approval request;
- ProcessInstanceNode represents a step in an instance of an approval process;
- ProcessInstanceStep represents one work item in an approval process; and
- ProcessInstanceHistory shows all steps and pending approval requests associated with an approval process
The ERD is as follows:
Second-class objects can be frustrating. They don’t support Triggers or Triggered Flows, Validation Rules, and they don’t appear in the Object Manager – just to name a few annoyances.
Anyway, I needed to query ProcessInstance and one of the child objects. This can be accomplished by querying ProcessInstance and using a subquery, but the subqueries need to query the Child Relationship Name, as opposed to the object API name. I usually pull this information from the Object Manager, which of course I couldn’t access. Ahh!
Luckily most modern IDEs have predictive text, so it wasn’t too hard to figure out the names of the relationships to query:
SELECT Id, ProcessDefinition.Name,
(SELECT Comments, Actor.Name, SystemModStamp, StepStatus FROM Steps),
(SELECT Id, ProcessNodeName, NodeStatus, LastActor.Name FROM Nodes),
(SELECT Id, Actor.Name FROM Workitems),
(SELECT Id, Comments FROM StepsAndWorkitems)
FROM ProcessInstance
WHERE ID =: piId;