Ext.data.JsonP.tree({"title":"Trees","guide":"

Trees

\n
\n

Contents

\n
    \n
  1. The Node Interface
  2. \n
  3. Visually changing your tree
  4. \n
  5. Multiple columns
  6. \n
  7. Adding nodes to the tree
  8. \n
  9. Loading and Saving Tree Data using a Proxy
  10. \n
\n
\n\n
\n\n

The Tree Panel Component is one of the most versatile Components in Ext JS and is an excellent tool for displaying heirarchical data in an application. Tree Panel extends from the same class as Grid Panel, so all of the benefits of Grid Panels - features, extensions, and plugins can also be used on Tree Panels. Things like columns, column resizing, dragging and dropping, renderers, sorting and filtering can be expected to work similarly for both components.

\n\n

Let's start by creating a very simple Tree.

\n\n
Ext.create('Ext.tree.Panel', {\n    renderTo: Ext.getBody(),\n    title: 'Simple Tree',\n    width: 150,\n    height: 150,\n    root: {\n        text: 'Root',\n        expanded: true,\n        children: [\n            {\n                text: 'Child 1',\n                leaf: true\n            },\n            {\n                text: 'Child 2',\n                leaf: true\n            },\n            {\n                text: 'Child 3',\n                expanded: true,\n                children: [\n                    {\n                        text: 'Grandchild',\n                        leaf: true\n                    }\n                ]\n            }\n        ]\n    }\n});\n
\n\n

This Tree Panel renders itself to the document body. We defined a root node that is expanded by default. The root node has three children, the first two of which are leaf nodes which means they cannot have any children. The third node is not a leaf node and has has one child leaf node. The text property is used as the node's text label. See Simple Tree for a live demo.

\n\n

Internally a Tree Panel stores its data in a TreeStore. The above example uses the root config as a shortcut for configuring a store. If we were to configure the store separately, the code would look something like this:

\n\n
var store = Ext.create('Ext.data.TreeStore', {\n    root: {\n        text: 'Root',\n        expanded: true,\n        children: [\n            {\n                text: 'Child 1',\n                leaf: true\n            },\n            {\n                text: 'Child 2',\n                leaf: true\n            },\n            ...\n        ]\n    }\n});\n\nExt.create('Ext.tree.Panel', {\n    title: 'Simple Tree',\n    store: store,\n    ...\n});\n
\n\n

For more on Stores see the Data Guide.

\n\n

The Node Interface

\n\n

In the above examples we set a couple of different properties on tree nodes. But what are nodes exactly? As mentioned before, the Tree Panel is bound to a TreeStore. A Store in Ext JS manages a collection of Model instances. Tree nodes are simply Model instances that are decorated with a NodeInterface. Decorating a Model with a NodeInterface gives the Model the fields, methods and properties that are required for it to be used in a tree. The following is a screenshot that shows the structure of a node in the developer tools.

\n\n

\"A

\n\n

In order to see the full set of fields, methods and properties available on nodes, see the API documentation for the NodeInterface class.

\n\n

Visually changing your tree

\n\n

Let's try something simple. When you set the useArrows configuration to true, the Tree Panel hides the lines and uses arrows as expand and collapse icons.

\n\n

\"Arrows\"

\n\n

Setting the rootVisible property to false visually removes the root node. By doing this, the root node will automatically be expanded. The following image shows the same tree with rootVisible set to false and lines set to false.

\n\n

\"Root

\n\n

Multiple columns

\n\n

Since Tree Panel extends from the same base class as Grid Panel adding more columns is very easy to do.

\n\n
var tree = Ext.create('Ext.tree.Panel', {\n    renderTo: Ext.getBody(),\n    title: 'TreeGrid',\n    width: 300,\n    height: 150,\n    fields: ['name', 'description'],\n    columns: [{\n        xtype: 'treecolumn',\n        text: 'Name',\n        dataIndex: 'name',\n        width: 150,\n        sortable: true\n    }, {\n        text: 'Description',\n        dataIndex: 'description',\n        flex: 1,\n        sortable: true\n    }],\n    root: {\n        name: 'Root',\n        description: 'Root description',\n        expanded: true,\n        children: [{\n            name: 'Child 1',\n            description: 'Description 1',\n            leaf: true\n        }, {\n            name: 'Child 2',\n            description: 'Description 2',\n            leaf: true\n        }]\n    }\n});\n
\n\n

The columns configuration expects an array of Ext.grid.column.Column configurations just like a Grid Panel would have. The only difference is that a Tree Panel requires at least one column with an xtype of 'treecolumn'. This type of column has tree-specific visual effects like depth, lines and expand and collapse icons. A typical Tree Panel would have only one 'treecolumn'.

\n\n

The fields configuration is passed on to the Model that the internally created Store uses (See the Data Guide for more information on Models). Notice how the dataIndex configurations on the columns map to the fields we specified - name and description.

\n\n

It is also worth noting that when columns are not defined, the tree will automatically create one single treecolumn with a dataIndex set to 'text'. It also hides the headers on the tree. To show this header when using only a single column set the hideHeaders configuration to 'false'.

\n\n

Adding nodes to the tree

\n\n

The root node for the Tree Panel does not have to be specified in the initial configuration. We can always add it later:

\n\n
var tree = Ext.create('Ext.tree.Panel');\ntree.setRootNode({\n    text: 'Root',\n    expanded: true,\n    children: [{\n        text: 'Child 1',\n        leaf: true\n    }, {\n        text: 'Child 2',\n        leaf: true\n    }]\n});\n
\n\n

Although this is useful for very small trees with only a few static nodes, most Tree Panels will contain many more nodes. So let's take a look at how we can programmatically add new nodes to the tree.

\n\n
var root = tree.getRootNode();\n\nvar parent = root.appendChild({\n    text: 'Parent 1'\n});\n\nparent.appendChild({\n    text: 'Child 3',\n    leaf: true\n});\n\nparent.expand();\n
\n\n

Every node that is not a leaf node has an appendChild method which accepts a Node, or a config object for a Node as its first parameter, and returns the Node that was appended. The above example also calls the expand method to expand the newly created parent.

\n\n

\"Appending

\n\n

Also useful is the ability to define children inline when creating the new parent nodes. The following code gives us the same result.

\n\n
var parent = root.appendChild({\n    text: 'Parent 1',\n    expanded: true,\n    children: [{\n        text: 'Child 3',\n        leaf: true\n    }]\n});\n
\n\n

Sometimes we want to insert a node into a specific location in the tree instead of appending it. Besides the appendChild method, Ext.data.NodeInterface also provides insertBefore and insertChild methods.

\n\n
var child = parent.insertChild(0, {\n    text: 'Child 2.5',\n    leaf: true\n});\n\nparent.insertBefore({\n    text: 'Child 2.75',\n    leaf: true\n}, child.nextSibling);\n
\n\n

The insertChild method expects an index at which the child will be inserted. The insertBefore method expects a reference node. The new node will be inserted before the reference node.

\n\n

\"Inserting

\n\n

NodeInterface also provides several more properties on nodes that can be used to reference other nodes.

\n\n\n\n\n

Loading and Saving Tree Data using a Proxy

\n\n

Loading and saving Tree data is somewhat more complex than dealing with flat data because of all the fields that are required to represent the hierarchical structure of the tree.\nThis section will explain the intricacies of working with tree data.

\n\n

NodeInterface Fields

\n\n

The first and most important thing to understand when working with tree data is how the NodeInterface class' fields work.\nEvery node in a Tree is simply a Model instance decorated with the NodeInterface's fields and methods.\nAssume for a moment that an application has a Model called Person. A Person only has two fields - id and name:

\n\n
Ext.define('Person', {\n    extend: 'Ext.data.Model',\n    fields: [\n        { name: 'id', type: 'int' },\n        { name: 'name', type: 'string' }\n    ]\n});\n
\n\n

At this point Person is just a plain vanilla Model. If an instance is created, it can easily be verified that it only has two fields by looking at its fields collection

\n\n
console.log(Person.prototype.fields.getCount()); // outputs '2'\n
\n\n

When the Person model is used in a TreeStore, something interesting happens. Notice the field count now:

\n\n
var store = Ext.create('Ext.data.TreeStore', {\n    model: 'Person',\n    root: {\n        name: 'Phil'\n    }\n});\n\nconsole.log(Person.prototype.fields.getCount()); // outputs '24'\n
\n\n

The Person model's prototype got 22 extra fields added to it just by using it in a TreeStore. All of these extra fields are defined on the NodeInterface\nclass and are added to the Model's prototype the first time an instance of that Model is used in a TreeStore (by setting it as the root node).

\n\n

So what exactly are these 22 extra fields, and what do they do? A quick look at the NodeInterface source code reveals that it decorates the Model with the following fields.\nThese fields are used internally to store information relating to the tree's structure and state:

\n\n
{name: 'parentId',   type: idType,    defaultValue: null},\n{name: 'index',      type: 'int',     defaultValue: null, persist: false},\n{name: 'depth',      type: 'int',     defaultValue: 0, persist: false},\n{name: 'expanded',   type: 'bool',    defaultValue: false, persist: false},\n{name: 'expandable', type: 'bool',    defaultValue: true, persist: false},\n{name: 'checked',    type: 'auto',    defaultValue: null, persist: false},\n{name: 'leaf',       type: 'bool',    defaultValue: false},\n{name: 'cls',        type: 'string',  defaultValue: null, persist: false},\n{name: 'iconCls',    type: 'string',  defaultValue: null, persist: false},\n{name: 'icon',       type: 'string',  defaultValue: null, persist: false},\n{name: 'root',       type: 'boolean', defaultValue: false, persist: false},\n{name: 'isLast',     type: 'boolean', defaultValue: false, persist: false},\n{name: 'isFirst',    type: 'boolean', defaultValue: false, persist: false},\n{name: 'allowDrop',  type: 'boolean', defaultValue: true, persist: false},\n{name: 'allowDrag',  type: 'boolean', defaultValue: true, persist: false},\n{name: 'loaded',     type: 'boolean', defaultValue: false, persist: false},\n{name: 'loading',    type: 'boolean', defaultValue: false, persist: false},\n{name: 'href',       type: 'string',  defaultValue: null, persist: false},\n{name: 'hrefTarget', type: 'string',  defaultValue: null, persist: false},\n{name: 'qtip',       type: 'string',  defaultValue: null, persist: false},\n{name: 'qtitle',     type: 'string',  defaultValue: null, persist: false},\n{name: 'children',   type: 'auto',   defaultValue: null, persist: false}\n
\n\n

NodeInterface Fields are Reserved Names

\n\n

It is important to note that all of the above field names should be treated as \"reserved\" names. For example, it is not allowed to have a field called \"parentId\"\nin a Model, if that Model is intended to be used in a Tree, since the Model's field will override the NodeInterface field. The exception to this rule is\nwhen there is a legitimate need to override the persistence of a field.

\n\n

Persistent Fields vs Non-persistent Fields and Overriding the Persistence of Fields

\n\n

Most of NodeInterface's fields default to persist: false. This means they are non-persistent fields by default. Non-persistent fields will not be saved via\nthe Proxy when calling the TreeStore's sync method or calling save() on the Model. In most cases, the majority of these fields can be left at their default\npersistence setting, but there are cases where it is necessary to override the persistence of some fields. The following example demonstrates how to override\nthe persistence of a NodeInterface field. When overriding a NodeInterface field it is important to only change the persist property. name, type, and defaultValue\nshould never be changed.

\n\n
// overriding the persistence of NodeInterface fields in a Model definition\nExt.define('Person', {\n    extend: 'Ext.data.Model',\n    fields: [\n        // Person fields\n        { name: 'id', type: 'int' },\n        { name: 'name', type: 'string' }\n\n        // override a non-persistent NodeInterface field to make it persistent\n        { name: 'iconCls', type: 'string',  defaultValue: null, persist: true },\n    ]\n});\n
\n\n

Let's take a more in-depth look at each NodeInterface field and the scenarios in which it might be necessary to override its persist property.\nIn each example below it is assumed that a Server Proxy is being used unless otherwise noted.

\n\n

Persistent by default:

\n\n\n\n\n

Non-persistent by default:

\n\n\n\n\n

Loading Data

\n\n

There are two ways to load tree data. The first is to for the proxy to fetch the entire tree all at once. For larger trees where loading everything\nat once is not ideal, it may be preferable to use the second method - dynamically loading the children for each node when it is expanded.

\n\n

Loading the Entire Tree

\n\n

Internally the tree only loads data in response to a node being expanded. However the entire hierarchy can be loaded if the proxy retrieves a nested object\ncontaining the whole tree structure. To accomplish this, initialize the TreeStore's root node to expanded:

\n\n
Ext.define('Person', {\n    extend: 'Ext.data.Model',\n    fields: [\n        { name: 'id', type: 'int' },\n        { name: 'name', type: 'string' }\n    ],\n    proxy: {\n        type: 'ajax',\n        api: {\n            create: 'createPersons',\n            read: 'readPersons',\n            update: 'updatePersons',\n            destroy: 'destroyPersons'\n        }\n    }\n\n});\n\nvar store = Ext.create('Ext.data.TreeStore', {\n    model: 'Person',\n    root: {\n        name: 'People',\n        expanded: true\n    }\n});\n\nExt.create('Ext.tree.Panel', {\n    renderTo: Ext.getBody(),\n    width: 300,\n    height: 200,\n    title: 'People',\n    store: store,\n    columns: [\n        { xtype: 'treecolumn', header: 'Name', dataIndex: 'name', flex: 1 }\n    ]\n});\n
\n\n

Assume that the readPersons url returns the following json object

\n\n
{\n    \"success\": true,\n    \"children\": [\n        { \"id\": 1, \"name\": \"Phil\", \"leaf\": true },\n        { \"id\": 2, \"name\": \"Nico\", \"expanded\": true, \"children\": [\n            { \"id\": 3, \"name\": \"Mitchell\", \"leaf\": true }\n        ]},\n        { \"id\": 4, \"name\": \"Sue\", \"loaded\": true }\n    ]\n}\n
\n\n

That's all that's needed to load the entire tree.

\n\n

\"Tree

\n\n

Important items to note:

\n\n\n\n\n

Dynamically Loading Children When a Node is Expanded

\n\n

For larger trees it may be desirable to only load parts of the tree by loading child nodes only when their parent node is expanded. Suppose in the above example,\nthat the node with name \"Sue\" does not have its loaded field set to true by the server response. The Tree would display an expander icon next to the node.\nWhen the node is expanded the proxy will make another request to the readPersons url that looks something like this:

\n\n
/readPersons?node=4\n
\n\n

This tells the server to retrieve the child nodes for the node with an id of 4. The data should be returned in the same format as the data that was used to load the root node:

\n\n
{\n    \"success\": true,\n    \"children\": [\n        { \"id\": 5, \"name\": \"Evan\", \"leaf\": true }\n    ]\n}\n
\n\n

Now the Tree looks something like this:

\n\n

\"Tree

\n\n

Saving Data

\n\n

Creating, updating, and deleting nodes is handled automatically and seamlessly by the Proxy.

\n\n

Creating a New Node

\n\n
// Create a new node and append it to the tree:\nvar newPerson = Ext.create('Person', { name: 'Nige', leaf: true });\nstore.getNodeById(2).appendChild(newPerson);\n
\n\n

Since the proxy is defined directly on the Model, the Model's save() method can be used to persist the data:

\n\n
newPerson.save();\n
\n\n

Updating an Existing Node

\n\n
store.getNodeById(1).set('name', 'Philip');\n
\n\n

Removing a Node

\n\n
store.getRootNode().lastChild.remove();\n
\n\n

Bulk Operations

\n\n

After creating, updating, and removing several nodes, they can all be persisted in one operation by calling the TreeStore's sync() method:

\n\n
store.sync();\n
\n"});