How to Render Parent, Child, and Grandchild Rows in a Salesforce Document

A practical guide to printing three levels of related records (for example Account, Opportunity, Line Item) in a Salesforce PDF or Word document, with the SOQL, the grouping logic, and the pitfalls that break it.
A flat list of line items is easy. The moment a document needs a hierarchy, things get hard: an Order with Order Groups, each holding Order Items. A Project with Phases, each holding Tasks. A Quote with Bundles, each holding Options.
That is a parent, child, and grandchild layout, and most Salesforce document tools handle it badly. This guide explains how the data has to be shaped, three ways to render it, and the mistakes that cause empty sections, duplicated rows, and hit limits.
Step 1: Understand what the document actually needs
Before touching a template, write the target layout on paper:
Project: Website Redesign
Phase 1: Discovery
- Stakeholder interviews 40h
- Competitive audit 24h
Phase 2: Build
- Design system 80h
- Front-end 120h
Three levels means three loops, one inside the other. Every approach below is some way of getting a list of phases, where each phase carries its own list of tasks, to the template.
Step 2: Get the data in one shape
You have two options for fetching the data.
Option A: Nested SOQL subqueries
Salesforce lets you query children inside a parent query. Since API version 58.0 you can nest parent-to-child subqueries up to five levels deep:
SELECT Name,
(SELECT Name, Sequence__c,
(SELECT Name, Hours__c FROM Tasks__r ORDER BY Sequence__c)
FROM Phases__r ORDER BY Sequence__c)
FROM Project__c
WHERE Id = :projectId
The result is already a tree: project.Phases__r[i].Tasks__r[j]. This is the cleanest option when you control the code, because ordering and filtering happen in the query.
Watch for these limits:
- A query can contain a limited number of subqueries, and each relationship subquery returns a capped number of rows.
- Heap size counts the whole tree. A 3-level tree with thousands of rows can hit the 6 MB synchronous heap limit.
- Subqueries cannot be filtered by anything computed in Apex. You filter in SOQL or after the fact.
Option B: Flat queries stitched together in Apex
If your hierarchy crosses lookups that do not support subqueries, or you need computed filters, query each level separately and group in memory:
Map<Id, List<Task__c>> tasksByPhase = new Map<Id, List<Task__c>>();
for (Task__c t : [
SELECT Name, Hours__c, Phase__c
FROM Task__c
WHERE Phase__r.Project__c = :projectId
ORDER BY Phase__r.Sequence__c, Sequence__c
]) {
if (!tasksByPhase.containsKey(t.Phase__c)) {
tasksByPhase.put(t.Phase__c, new List<Task__c>());
}
tasksByPhase.get(t.Phase__c).add(t);
}
You then wrap each phase and its tasks in a small inner class and hand the list of wrappers to the page. It is more code, but it works for any shape of data.
Step 3: Render the three levels
In a Visualforce PDF
Nest apex:repeat tags, one per level:
<apex:repeat value="{!phases}" var="phase">
<h3>{!phase.name}</h3>
<table>
<apex:repeat value="{!phase.tasks}" var="task">
<tr>
<td>{!task.name}</td>
<td>{!task.hours}</td>
</tr>
</apex:repeat>
</table>
</apex:repeat>
For a true third level inside the table, nest a third apex:repeat within the second. Keep each level in its own wrapper property so the markup stays readable.
In a Word template merge
Tag-based Word merge tools usually use a start and end marker for each repeating region, and nested regions are marked with nested start and end tags. The rules differ by tool, but they share a trap: the inner region must sit entirely within the outer region, and the tags must live in the same table or paragraph structure. If an end tag lands in a different table cell than its start tag, Word splits the XML in a way the merge engine cannot recover from, and you get rows that vanish or repeat forever.
Practical rules:
- Put each loop's start and end tags in the same row (or the same paragraph) whenever possible.
- Use one table per level, or a table-in-table, rather than trying to interleave levels in a single grid.
- Type tags in a plain-text editor and paste them in, so Word does not insert invisible formatting runs in the middle of a tag.
In OmniStudio-style or JSON-driven tools
These tools expect a JSON tree. You assemble it in a data mapper or an Apex step, and the template iterates phases then tasks. The common failure is a flattened array: the mapper returns tasks in a separate list, and the template cannot tell which phase each belongs to. Make sure the output nests the children inside their parent.
Step 4: Handle subtotals per level
A hierarchy almost always needs totals: hours per phase, and a grand total for the project.
- Phase total: compute it where you build the tree, as
sum(tasks.hours), and store it on the phase wrapper. Do not recalculate in the template. - Grand total: sum the phase totals, or use a roll-up summary field on the parent when the relationship is master-detail.
If the second level is a lookup rather than master-detail, roll-up summary fields are not available. In that case, compute in Apex or with a Flow before generation.
Some template engines total each level in the template instead. ZeroExport, for example, scopes an aggregate such as {{Tasks.sum(Hours__c)}} to the phase it sits under, and can group rows by a picklist or a parent record with a subtotal row per group, over lookups as well as master-detail. See multi-level grouping and subtotals in Salesforce document templates.
Common pitfalls
Empty parents print a header and nothing else. A phase with no tasks still renders its heading. Filter empty phases when you build the tree, or hide the heading when its list is empty (see how to add conditional visibility to a Salesforce document).
Ordering is lost. A subquery without an ORDER BY returns rows in no guaranteed order. Always sort every level, usually by a sequence field, not by name.
The grandchild loop shows the wrong rows. This happens when you query all tasks once and loop the full list inside every phase. Each phase must iterate only its own tasks.
Performance falls off a cliff. Three nested loops over large lists are slow in any rendering engine. Limit the data to what is printed, and avoid querying inside a loop.
A table breaks across pages mid-group. Add page-break rules so a phase heading never sits alone at the bottom of a page.
Frequently asked questions
How many levels deep can Salesforce SOQL go? Parent-to-child subqueries can nest up to five levels in current API versions, and child-to-parent traversal also goes up to five levels. Document layouts rarely need more than three.
Can I do this without Apex? Yes, when the hierarchy follows standard relationships and your tool accepts nested subqueries or a relationship tree. When you need computed filters or cross-object grouping, some code or a Flow is usually unavoidable. Grouping and per-group subtotals no longer need code in engines that group in the template; see multi-level grouping and subtotals.
Why do my grandchild rows repeat under every parent? The inner loop is iterating a flat list instead of the parent's own child list. Bind the inner loop to the child collection of the current parent, not to a page-level list.
Should I flatten the data instead? Flattening, with one row per task and the phase name repeated, is simpler to build and works for plain tables. Use a true hierarchy when each level needs its own heading, subtotal, or layout.
Summary
Rendering parent, child, and grandchild data comes down to two decisions: shape the data as a tree before the template sees it, and keep each loop bound to its own parent's children. Get those right and the three levels, the subtotals, and the page breaks fall into place.
For more on table layouts that hold up with real data, see complex table rendering in Salesforce documents and repeating rows without start and end tags.
Ready to try ZeroExport?
Start generating documents directly in your Salesforce org. No integrations, no setup overhead, no complexity.