Ext Tree and Coldfusion Example

The EXT tree is, in my opinion, a much better implementation of a dynamic ajax tree than what the yahoo utility toolkit starts out with, and subsequently what Adobe decided to use for the CFTREE tag. Once again I am really amazed at the quality work that Jack and his crew have done.

The tree itself is relatively simple to set up as either a static tree or dynamic tree.

In the example code I will be showing I have set up the tree to have a lazy loader. This means that I will only be showing the root (and in this case the first set of children) of the tree and each time a node is clicked a call will be made to populate that nodes children.

<html>
   <head>
      <title>EXT TREE Example</title>
<script type="text/javascript" src="resources/javascript/yui-utilities.js"></script>
<script type="text/javascript" src="resources/javascript/ext-yui-adapter.js"></script>
<script type="text/javascript" src="resources/javascript/ext-all.js"></script>
<link rel="stylesheet" type="text/css" href="resources/css/ext-all.css" />
<script language="javascript">
var iTree = function(){
var root, tree;
return {
init : function(){
//define your ext tree
var Tree = Ext.tree;
//set up the data loader for the tree
var loader = new Tree.TreeLoader({dataUrl:'com/gg/fileExplorer.cfc?method=getDirectoriesExt&itempath=&itemvalue='});
                  //set up the lazy loader here
         loader.on('beforeload', function(loader, node){
                     //again the url to your function to return the nodes for the selected child
                     loader.dataUrl = 'com/gg/fileExplorer.cfc?method=getDirectoriesExt&itempath=&itemvalue='+node.attributes.id;
                  });
                  //set the options
tree = new Tree.TreePanel('treeView', {
animate:true,
loader: loader,
enableDD:false, //set this to true if you want to enable drag and drop
containerScroll: true
});
// set the root node
root = new Tree.AsyncTreeNode({
text: 'ROOT',
draggable:false,
id:'/'
});
tree.setRootNode(root);
// render the tree
tree.render();
root.expand();//causes the tree to get its immediate children
}
};
}();

Ext.onReady(function(){iTree.init();});
</script>
</head>
<body>
   <div id="treeView"></div>
</body>
</html>

The Javascript code it's self should be pretty straight forward. I would encourage you to check out the API documentation for EXT if you haven't already. In case you haven't taken a look at the documentation I will quickly run through a couple of things here for you.

var iTree = function(){
...
return {
init : function(){
};
...
}();
This part of the code creates a Javascript "class" named iTree, with a public method named init. In the init function we set up our tree and finally at the end of the init function we render the tree and expand the root.

If you are a novice Javascript programmer this may all look a little complicated, well it is the beginnings of OOJS and I would encourage you to take a look at Douglas Crockford's javascript website.

So we now have our iTree class but we still need to initialize it. We do that with this little piece of code.

Ext.onReady(function(){iTree.init();});

This line of code executes after the entire document has been parsed or "onReady". The onReady method as defined in the API docs:

onReady
public function onReady(Function fn, Object scope, boolean override)
Fires when the document is ready (before onload and before images are loaded). Shorthand of Ext.EventManager.onDocumentReady.
Parameters:

* fn : Function
The method the event invokes
* scope : Object
An object that becomes the scope of the handler
* override : boolean
If true, the obj passed in becomes the execution scope of the listener

Returns:

* void

This function(){iTree.init();} function is executed as the definitions states immediately after the document is ready.

Once iTree.init is fired our tree exists and should look like this (if you have all the resources set up correctly)

Now onto the backend

In this example I am using Coldfusion 8 but if you are using an earlier version of coldfusion you can remove the attributes returnformat="plain" and instead of using a return you can simply output the results inside of a cfoutput tag.

<cffunction name="getDirectoriesExt" access="remote" returnformat="plain" returntype="string">
   <cfargument name="itemPath" type="string" required="yes"/>
   <cfargument name="itemValue" type="string" required="yes"/>

   <cfset var baseDir ="#expandpath('/')#"/>
   <cfset var result =arrayNew(1)/>
   <cfset var sbaseDir=""/>

   <cfif arguments.itemValue neq ''>
      <cfset sbaseDir ="#basedir##itemvalue#"/>
      <cfdirectory action="list" name="allDirs" directory="#sbaseDir#"/>
      <cfquery name="dirs" dbtype="query">
         select name
         from alldirs
         where type='Dir'
      </cfquery>
      <cfset tree='['>
      <cfoutput query="dirs">
         <cfset hasChildren = hasSubDirs('#sbaseDir#/#name#')>
         <cfset tree= tree & '{"text":"#name#","id":"#itemvalue#/#name#",'>
         <cfif not hasChildren>
            <cfset tree= tree &'"leaf":true,'>
         </cfif>
         <cfset tree = tree &'"cls":"'>
         <cfif not hasChildren>
            <cfset tree=tree & 'file'>
                        <cfelse>
            <cfset tree=tree &'folder'>
                        </cfif>
         <cfset tree=tree & '"},'/>

      </cfoutput>
      <cfset tree = left(tree,len(tree)-1)/>
      <cfset tree = tree & ']'/>
   </cfif>
   <cfreturn tree/>
</cffunction>

If you have any questions post a comment below.

Happy Coding...

Related Blog Entries

Comments
IRz's Gravatar does not work. no errors. displays the root but nothing else. the only thing i changed was the path to the javascript files, but they all load, and the path to fileexplorer.cfc and it loads fine.
cf8, iis5, ff 2, win
# Posted By IRz | 10/4/07 2:56 PM
Gary Gilbert's Gravatar I copy and pasted the above code from a working example onto the post. I also put up an online example with the same code here:http://www.garyrgilbert.com/dev/examples/treetest.... I made a slight change to the function because its a CF6.1 hosting environment.

The only changes to the function are as follows:
1) Removed returntype="string"
2) Added of output="yes"
3) removed <cfreturn tree/> and replaced it with <cfoutput>#tree#</cfoutput>

If you don't have firebug installed on firefox I would highly recommend it. It will help you figure out whats going on in the background and return any errors you have.
# Posted By Gary Gilbert | 10/4/07 3:30 PM
Wes Chen's Gravatar I just like to see how the function work and try to play around it. But I have some questions.
Does the code need those javascript files "resources/javascript/yui-utilities.js" and CSS file "resources/css/ext-all.css"...?
If it did need it, where can I get it? Thanks.
# Posted By Wes Chen | 2/5/08 6:04 PM
Gary Gilbert's Gravatar @Wes

You can download the files from http://www.extjs.com
# Posted By Gary Gilbert | 2/6/08 3:08 AM