Setting up and displaying hierarchical data in Drupal 7


In Drupal 7, there's no forward-looking native method for managing hierarchical data. We do have the Book module, but it's old and hard-codes things that can be done in a more general way. For example, it's using its own database table instead of using the Field API.

We can do a better job of creating book sections and subsections, say, with some contributed modules and a little bit of recursion.

  1. Install and enable Entity Reference, Views, Views tree (optional, see below) and Viewfield.
  2. Create a content type for your hierarchical data. Let's call it "Section".
  3. Add an Entity Reference field for nodes, called "Parent" (or "Parents" if you want multiple inheritance - change the cardinality from "1" to whatever you like) to your Section content type.
  4. Create a table of contents (TOC) with Views tree. If you really don't want to add another module here, you can instead have all top-level nodes reference a root node, which is really the TOC. It all depends on whether you'd rather have another module or slightly more complex data.
  5. Create a new view, "Subsections", that displays all nodes with a given parent node ID (passed in as an argument).
  6. Add a Viewfield field to the Section content type defined as the Subsections view, with the current node ID as the argument.
  7. Now when you look at a Section node, you'll see all subsections as well, including sub-subsections and sub-sub-subsections etc. because of recursion; each child node is displayed in the parent node recursively because of Viewfield.

This approach works up to a point, but it doesn't scale terribly well. If you've got a very large number of nodes, you'll run into performance (specifically memory) problems because of the way Views handles recursion. Basically, it brings far too much into memory when setting up the data structures. So, if you've got tonnes of records, you'll have to tweak this somewhat.

Hopefully, there will be better tools for this this in the future. The Tree module looks like it may be heading in this direction.

Add new comment