Blog Archive

ExtJs 4 Tree Panel sample code - Java Servlet, JSON and MySQL

This tutorial covers the following topics
  • How to create a ExtJs 4 Tree Panel
  • Expanding and collapsing of the Tree Nodes
  • Get Tree node data from Java Servlet in JSON format
  • Database behind the Tree node is MySQL
  • Tree node click event to capture the node value and other attributes that can be useful for further processing
  • Basic Drag and Drop plugin
  • Asynchronous loading through a TreeStore and AjaxProxy.

The TreePanel Ext.tree.Panel provides tree-structured UI representation of tree-structured data. A TreePanel must be bound to a Ext.data.TreeStore. The TreeStore is a store implementation that is backed by by an Ext.data.Tree. It provides convenience methods for loading nodes, as well as the ability to use the hierarchical tree structure combined with a store.In our Tree example we start with Continents, from there you can drill down to Regions and then to Countries.


ExtJs 4 Tree Panel example using Java Servlet JSON response and MySQL
ExtJs 4 Tree Panel example using Java Servlet JSON response and MySQL
ExtJs 4 Tree Panel example using Java Servlet JSON response and MySQL

Application starting point index.html

<html>
<head>
    <title>ExtJs 4 Tree Panel Example using Java Servlet and MySQL database</title>

    <link rel="stylesheet" type="text/css" href="extjs/resources/css/ext-all.css">
   
    <script type="text/javascript" src="extjs/ext-all-debug.js"></script>
    <script type="text/javascript" src="app.js"></script>

</head>
<body></body>
</html>

Application JavaScript file app.js

Ext.Loader.setConfig({ 
    enabled: true 
    });

Ext.application({
    name: 'TR',

    appFolder: 'app',
   
    controllers: [
                  'Countries'
              ],

    launch: function() {
        Ext.create('Ext.container.Viewport', {
            items: [
                {
                    xtype: 'label',
                    html: '<b>ExtJs 4 Tree Panel Example</b>'
                },
                {
                    xtype: 'countryTree',
                }
            ]
        });
    }
});

JavaScript source file for the Tree Store Countries.js

Ext.define('TR.store.Countries', {
    extend: 'Ext.data.TreeStore',
    proxy: {
        type: 'ajax',
        url: 'CountryServlet'
    },
    root: {
        text: 'Tree display of Countries',
        id: 'myTree',
        expanded: true
    },
    folderSort: true,
    sorters: [{
        property: 'text',
        direction: 'ASC'
    }]
   
});

JavaScript source file for the Tree Panel View CountryTree.js

Ext.define('TR.view.CountryTree', {
    extend: 'Ext.tree.Panel',
    alias: 'widget.countryTree',
    store: 'Countries',
    viewConfig: {
        plugins: {
            ptype: 'treeviewdragdrop'
        }
    },
    height: 600,
    width: 400,
    useArrows: true,
    dockedItems: [{
        xtype: 'toolbar',
        items: [{
            text: 'Expand All',
        }, {
            text: 'Collapse All',
        }]
    }]
});

JavaScript source file for the application controller Countries.js

Ext.define('TR.controller.Countries', {
            extend : 'Ext.app.Controller',

            //define the stores
            stores : ['Countries'],
            //define the models
            models : [],
            //define the views
            views : ['CountryTree'],
            refs: [{
                    ref: 'myCountryTree', 
                    selector: 'countryTree'
                    }
            ],  
           
            init : function() {
                this.control({
                   
                    'viewport' : {
                        render : this.onPanelRendered
                    },
                    'countryTree button[text=Expand All]' : {
                        click : this.expandAll   
                    },
                    'countryTree button[text=Collapse All]' : {
                        click : this.collapseAll   
                    },
                    'countryTree' : {
                        itemclick : this.treeItemClick   
                    }
                });
            },

            onPanelRendered : function() {
                //just a console log to show when the panel si rendered
                console.log('The panel was rendered');
            },
           
            expandAll : function() {
                //expand all the Tree Nodes
                var myTree = this.getMyCountryTree();
                myTree.expandAll();
            },
           
            collapseAll : function() {
                //expand all the Tree Nodes
                var myTree = this.getMyCountryTree();
                myTree.collapseAll();
            },
           
            treeItemClick : function(view, record) {
                //some node in the tree was clicked
                //you have now access to the node record and the tree view
                Ext.Msg.alert('Clicked on a Tree Node', 
                    'Node id: ' + record.get('id') + '\n' +
                    'Node Text: ' + record.get('text') + '\n' +
                    'Parent Node id: ' + record.get('parentId') + '\n' +
                    'Is it a leaf?: ' + record.get('leaf') + '\n' +
                    'No of Children: ' + record.childNodes.length
                );
                //now you have all the information about the node
                //Node id
                //Node Text
                //Parent Node
                //Is the node a leaf?
                //No of child nodes
                //......................
                //go do some real world processing
            }
           
    });

Sample JSON response from the Servlet


ExtJs 4 Tree Panel example using Java Servlet JSON response and MySQL
Click here for next Chapter


22 comments :

  1. Hi, Very thank you.You've helped me a lot of.

    ReplyDelete
  2. Hey,
    Good article.Can you please post how the JSON format should be?
    Thanks in Advance.

    ReplyDelete
  3. Added a sample JSON format for the Tree in the blog post above. Tree uses the Ext.data.NodeInterface for Tree Store loading.

    Please read the part 2 of this article to see the Java Bean that I created. The bean has some of the properties that are need for a Tree Node. I use Java bean to JSON convertor.

    ReplyDelete
  4. Please help. I have been struggling to get the js to read json generated on the fly. If I save the same json to a file and provide that filename in the store proxy url, it works fine and the data is displayed. With the on-the-fly generated json, I can see the json in my firebug response, but the TreePanel doesn't display it.

    I am appending my json below, just a few starting lines, please see if you can advise what could be wrong:
    ===================================
    [{'text':'ServicePlan2',id:'myTree/1',iconCls:'task-folder',cls:'foldercss','startdate':'12/01/2011','enddate':'',expanded:true,leaf:false,children:[{'text':'Category2',id:'myTree/2',iconCls:'task-folder',cls:'foldercss',leaf:false,children:[{'text':'SubCat21',id:'myTree/3',iconCls:'task-folder',cls:'foldercss',leaf:false,children:[{'text':'Exercise1',id:'myTree/4','startdate':'','enddate':'',iconCls:'task',cls:'leafcss',leaf:true}....................
    ================================
    I have emulated the app.js you have provided, also tried with the sencha TreeGrid example, but no success yet.

    ReplyDelete
  5. Are you getting any errors in your JavaScript console? The json that you provided did you get that from the network tab or just calling your URL in separate browser window?

    ReplyDelete
  6. The json few lines I have provided, is from the dump on the console of the string variable which is passed back. Can you provide me with a dump of your sample's json, which also contains some children? The one you have posted is only for top level nodes.

    No, I don't get any error in the js console, infact in firbug, I can even see the response with the valid json. Also since the same json when saved as a file and provided to the js, works fine, which makes me thonk that all required tags for the Tree display, are there in this json.

    ReplyDelete
  7. In my Tree Store I just get Top level JSON and then it makes the request by itself when you click on a node that is not a leaf and goes out and gets the children in another Ajax JSON request. If you click button expand all it makes JSON request for all nodes by itself.

    ReplyDelete
  8. Hi,
    Thanks for the reply...
    I want something to display like Parent and two childs under it. For which i want to frame the JSON format which can be loaded using the Store. Can you please suggest how to do this and correct the following JSON format.

    {
    "success":true,
    "rows":[
    {
    "text": "Parent,
    "leaf": false
    },
    {

    "text": "Child1",
    "leaf": true
    },
    {
    "text": "Child2",
    "leaf": true
    }
    ]
    }

    ReplyDelete
  9. Here is a sample JSON for Parent and children under it.

    [{
    "text": "My To Do",
    "cls": "folder",
    "expanded": true,
    "children": [{
    "text": "Go jogging",
    "leaf": true
    },{
    "text": "Take a nap",
    "leaf": true
    },{
    "text": "Climb Everest",
    "leaf": true,
    }]
    }]

    ReplyDelete
  10. I tried the way you have given it which was working fine. But i want some metadata in the JSON like "success". So i had created a format like below but it is not working.

    {
    "success": true,
    "rows": [
    {
    "text": "My To Do",
    "cls": "folder",
    "expanded": true,
    "children": [
    {
    "text": "Go jogging",
    "leaf": true
    },
    {
    "text": "Take a nap",
    "leaf": true
    },
    {
    "text": "Climb Everest",
    "leaf": true
    }
    ]
    }
    ]
    }

    ReplyDelete
  11. In your tree store proxy did you specify a reader? I haven't tried it yet. For example

    proxy: {
    type: 'ajax',
    url: 'YourServlet',
    reader: {
    type: 'json',
    root: 'rows',
    successProperty: 'success'
    },
    }

    ReplyDelete
  12. i am new to ext js .currently i am working on ext 4.0.i need some help to populate data in tree panel.

    example we are getting json data like {displayfeiled:testlayer,name:111}
    {displayfeiled:testlayer,name:1121}
    {displayfeiled:testlayer1,name:456}
    {displayfeiled:testlayer1,name:678}


    i want to populate data like
    +results..root1

    +testlayer child
    111.................child1
    1122
    +testlayer1
    456
    678
    .
    .
    .
    .

    pleas help how to assighed child elements dynamically

    ReplyDelete
  13. Hi BetterThanZero,

    First of all, very thank you for this article.

    My question: Could you show the servlet code (CountryServlet)?

    I don't understand that object return the servlet.

    Thanks in advance

    ReplyDelete
  14. nice work, but i need little more explanation for every java script file...pls help to understand the concept of Ext.data.Tree....

    ReplyDelete
  15. I don't have the servlet. How do I change it to work with hard-coded data? I replaced "proxy" section in Countires.store with:
    data : [
    {id: 'myTree/Here', leaf: 'false', text: 'North America'},
    {id: 'myTree/There', leaf: 'false', text: 'South America'},
    ],

    That did not do.
    Thanks

    ReplyDelete
  16. Hi
    Can any one tell me how to perform sorting on individual folders. For eg A tree can contain several folders and every folder has elements in it, In this application we have "North America", "Nordic countries" as folders and all contains child elements int them . how to perform sorting individually on each folders so one folder elements can be sorted ASC and other as DESC.I have an application where every folder needs to be sorted independently. An alternative solution is to create different treestores but this creates many treepanels which does not looks good.I want all the data in single panel.

    I will appreciate the help thanks

    ReplyDelete
    Replies
    1. I've got similar problem. I need to sort one node of the tree with all the rest intact.
      Did you solve it somehow?

      Delete
  17. Does anyone have tried to load controller depending of each item selected?

    ReplyDelete
  18. I want to use the treepanel to load controller dinamically ?
    My objetive is only load which the user needs at the moment.
    logica_Razon@hotmail.com

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. I didnt understand the var myTree = this.getMyCountryTree(); how you are getting this where is this method specify I didnt find this method in the js file.It was very nice and easy to understand tutorial.
    Can you help by sharing the code file for the same. thanks

    ReplyDelete