Coldfusion Tutorials



Spry Tutorials

Air Tutorials


Coldfusion 8 CFTree

In my previous tutorial I introduced one of the new Coldfusion 8 tags CFGRID. We set up the grid to bind to a coldfusion component and saw how the grid automatically comes with paging and sorting options built right in.

In this tutorial we will explore setting up a basic ajax driven tree using the CFTREE tag. The CFTREE tag existed before Coldfusion 8 but only now has it evolved to provide Ajax functionality. With the Ajax functionality we only need to load the nodes of the tree that we need "right now". When a user clicks on a node the bind attribute calls our component and a JSON data set is returned containing one level of children nodes for the node.

You set up your tree like so:


<cffunction name="getNodes" access="remote" returntype="array">
   <cfargument name="path" type="String" required="false" default=""/>
   <cfargument name="value" type="String" required="true" default=""/>
   <!--- set up return array --->
      <cfset var result= arrayNew(1)/>
      <cfset var s =""/>

      <!--- if arguments.value is empty the tree is being built for the first time --->
      <cfif arguments.value is "">
         <cfset x = 0/>
         <cfloop from="1" to="10" index="i">
            <cfset x = x+1/>
            <cfset s = structNew()/>
            <cfset s.value=#x#>
            <cfset s.display="Node #i#">
            <cfset arrayAppend(result,s)/>
         </cfloop>
      <cfelse>
      <!--- arguments.value is not empty --->
      <!--- to keep it simple we will only make children nodes --->
      <cfset y = 0/>
         <cfloop from="1" to="#arguments.value#" index="q">
            <cfset y = y + 1/>
            <cfset s = structNew()/>
            <cfset s.value=#q#>
            <cfset s.display="Leaf #q#">
            <cfset s.leafnode=true/>
            <cfset arrayAppend(result,s)/>
         </cfloop>
      </cfif>
   <cfreturn result/>
</cffunction>

While we create the array and simply return it, the bind argument on the CFTREE tag automatically sends an additional argument to the component asking it to return the results from the component as JSON we set our return type to array and coldfusion automagically converts it into JSON. Not too shaby eh?

Since the tree binds directly to the cfc, and is therefore called immediately on generating the tree, we need to make sure that we only generate the top level nodes once, that is why we check arguments.value at the very top. If arguments.value eq '' then we generate the parent nodes, otherwise we process the children.

The default styling of the cftree is pretty ugly so you may want to create your own styles.

 

In my next tutorial I will provide a more realistic tree example and additionall show you how to bind a tree to a grid so that when someone clicks on a node in the tree it causes a grid to be refreshed.