Creating a hierarchy list with Coldfusion

I came across a stored procedure that returns data in the following format:

The dilemma was how to display this so that each level was shown as a "sublevel" of the one above it. I easily accomplished this by keeping a list of the current levels. Each time a new level was added, I'd add this value to the "levelList". When that level was ended, I'd remove that value from "levelList". With this list, I would always know where I was. I would be able to end each unordered list and start new ones where needed.

Here's the result:

  • 1null
    • 2null
      • 31
        • 4D
        • 4E
      • 32
        • 4A
        • 4B
        • 4B
        • 4C
        • 4C
        • 4D
      • 33
        • 4A
    • 2null
      • 34
        • 4A
        • 4B
      • 35
      • 36

This creates a nice and easy to read format. Good for any sort of "tree" format you need, as long as the data is returned appropriately.

<cfset levelList = "">
<cfoutput query="queryResult">

   <!--- Is the last value in the list this level? --->
   <cfif listLast(levelList,",") IS NOT queryResult.level>
      <!--- Is this level in the levelList?
          If so, we need to close previous level down to this one now. --->

      <cfset levelListIndex = listFind(levelList,queryResult.level,",")>
      <cfif levelListIndex IS NOT 0>
         <cfset numberOfLevelsToRemove = listLen(levelList,",") - levelListIndex>
         <cfloop from="1" to="#numberOfLevelsToRemove#" index="i">
            <!--- Shorten the list to the appropriate level --->
            <cfset levelList = listDeleteAt(levelList,listLen(levelList,","))>
         <!--- Not in list, so start a new list level --->
         <cfset levelList = listAppend(levelList,queryResult.level)>

   <li> #queryResult.Name#</li>

   <!--- If this is the last row, then we need to close all unordered lists --->
   <cfif queryResult.currentRow IS queryResult.recordCount>


Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.