Friday, June 14, 2013

ExtJS: How to create static and dynamic trees

Today I am going to show how to create static and dynamic trees in ExtJS.
Create a static/dynamic tree like this one here.

Static/Basic trees: Creating static trees is quite easy and straightforward.
  • You will need a data model to hold your tree's data (Nodes).
  • Create a tree store and add the above model to it.
  • Set the above store to a tree panel and display the panel on the screen.
First we will create our model.
Let's create a "Car" model having different cars as its children.
You can see we have added our cars in the "children" property of the model.
"leaf" config is used to set whether the root will be a branch or a leaf.

  Ext.define('Car', {
    extend: 'Ext.data.Model',
    fields: [{
        name: 'name',
        type: 'string'
    }],
    proxy: {
        type: 'memory',
        data: {
            success: true,
            children: [{
                name: 'Cars',
                leaf: false, // this is a branch   
                expanded: false,
                children: [{
                    name: 'Mercedes-Benz',
                    leaf: true // this is a leaf node. It can't have children. Sad! :-(   
                }, {
                    name: 'Audi',
                    leaf: true
                }, {
                    name: 'Ferrari',
                    leaf: true
                }]
            }]
        }
    }
});

Now let's create a TreeStore object and attach our model to it.

  var store = Ext.create('Ext.data.TreeStore', {
    model: 'Car'
}); 

Now last step add our tree store to a Tree panel so that we can view our tree on screen.

  Ext.create('Ext.tree.Panel', {
    title: 'Car Simple Tree',
    width: 200,
    height: 150,
    store: store,
    rootVisible: false,
    lines: true, // will show lines to display hierarchy.    
    useArrows: true, //this is a cool feature - converts the + signs into Windows-7 like arrows. "lines" will not be displayed
    renderTo: Ext.getBody(),
    columns: [{
        xtype: 'treecolumn',
        dataIndex: 'name', // value field which will be displayed on screen   
        flex: 1
    }]
});

JSFiddle Demo
That's pretty much it. Just place this panel wherever you want your tree.

Now let's create a dynamic tree programmatically.

This is very much similar to what we did for the static tree.
Only difference is that we will have to add the children to our root node one by one.

 var carTree = new Ext.tree.TreePanel({
    title: 'Car Dynamic Tree',
    useArrows: true,
    lines: false,
    height: 150,
    width: 200,
    renderTo: Ext.getBody()
}); 

Now create a root node and add it to the tree panel using "setRootNode()" function.


var carRootNode = {
    name: 'Cars',
    text: 'Cars',
    expanded: true,
    leaf: false,
    children: []
};
//set root node
carTree.setRootNode(carRootNode);

Now if you have an array/store of data which you want to add to a tree, you need to iterate over each record and append the record to your root node.
In my case I have got a store. So I will iterate over my store, get each record and append it as a child.

 //get the root of the tree
var root = treeCarsPanel.getRootNode();

//iterate over your store and append your children one by one
carStore.each(function (rec) {
    var childAttrModel;
    //Create a new object and set it as a leaf node (leaf: true)  
    childAttrModel = {
        name: rec.data.name,
        text: rec.data.name,
        leaf: true,
    };
    // add/append this object to your root node 
    root.appendChild(childAttrModel);
}); 

Refresh your panel.

 treeCarsPanel.doLayout(); //refresh layouts form most cases  

And show your panel to your users.

treeCarsPanel.show();

JSFiddle Demo

That's it! we are done.
Hope you find this useful. Leave your comments/suggestions.

7 comments:

  1. I noticed that 'lines' config works only when useArrows is set to false.

    ReplyDelete
  2. That's right Sathish. I have mentioned this in the code comments where I have used 'useArrows'. You will either get the Windows XP or Windows 7 like theme

    ReplyDelete
  3. Hi,

    I was trying to run the sample Cars example (the code you have posted here) on my machine. I placed this code inside the script tag under .html file but the file is not displaying anything. The same code is getting executed from JSFiddle. Could you please let me know what is wrong with this? or what is what is the right way to include it in HTML file.

    ReplyDelete
    Replies
    1. Did you check the imports? What does your debugger tool say? run it in chrome and click f12. check the error

      Delete
  4. This is simply super!! I was struggling to build dynamic tree from store, above code is exactly what i was looking for. But in my requirement the tree has one more level of child nodes. could you please suggest me how to traverse through the leaf nodes of a tree store and append with the tree view?

    ReplyDelete
    Replies
    1. Hi Ramya Thanks for the above post,Could you please tel me how to render the data (nodes) from back end. I mean just tel me the steps to implementation in treepanel code through ajax request and json response

      Delete
  5. I would like to use this example but also create node for son of the root recursive, not just the root. is that possible?

    ReplyDelete