Guide applies to: classic

Trees

The Tree Panel Component is one of the most versatile Components in ExtJS and is an excellent tool for displaying hierarchical data in an application. Tree Panel extends from the same class as Grid Panel, so, most 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.

Let’s start by creating a very simple Tree.

Expand Code

JS Run

  1. Ext.create('Ext.tree.Panel', {
  2. renderTo: document.body,
  3. title: 'Simple Tree',
  4. width: 300,
  5. height: 250,
  6. root: {
  7. text: 'Root',
  8. expanded: true,
  9. children: [
  10. {
  11. text: 'Child 1',
  12. leaf: true
  13. },
  14. {
  15. text: 'Child 2',
  16. leaf: true
  17. },
  18. {
  19. text: 'Child 3',
  20. expanded: true,
  21. children: [
  22. {
  23. text: 'Grandchild',
  24. leaf: true
  25. }
  26. ]
  27. }
  28. ]
  29. }
  30. });

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.

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:

  1. var store = Ext.create('Ext.data.TreeStore', {
  2. root: {
  3. text: 'Root',
  4. expanded: true,
  5. children: [
  6. {
  7. text: 'Child 1',
  8. leaf: true
  9. },
  10. {
  11. text: 'Child 2',
  12. leaf: true
  13. },
  14. ...
  15. ]
  16. }
  17. });
  18. Ext.create('Ext.tree.Panel', {
  19. title: 'Simple Tree',
  20. store: store,
  21. ...
  22. });

Inheritance from Store

It is important to note that the Store persona of the TreeStore manages its own content according to the linked node structure based on the root node.

Only visible nodes are represented in the store. When a parent node is expanded, its child nodes are inserted into the store immediately following it. When that node is collapsed, those nodes are removed from the store.

Nodes which are deemed to not be visible in any way, whether due to ancestor collapsing, or due to filtering are NOT present in the Store’s record collection.

All nodes are still accessible through the tree hierarchy

The store is purely used to drive the user interface. Nodes are mapped into the view on a one-to-one basis.

To manipulate the content of the store, you must ALWAYS go through the interface that Ext.data.TreeModel provides to insert, append or remove nodes to or from other nodes.

Certain methods such as each and collect are re-implemented at the TreeStore level to offer access to all nodes in the structure instead of only the visible nodes that are in the flat Store persona.

The Node Interface

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 ExtJS manages a collection of Model instances.

In the absence of a configured Model type, the Store will use the Ext.data.TreeModel class to encapsulate the data. The is a Model subclass which has been decorated with 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.

A TreeModel instance illustrating the
TreeModel

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

The Models you define for use in your trees should extend the Ext.data.TreeModel class.

Changing your tree

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.

Arrows

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.

Root not visible and no lines

Multiple columns

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

Expand Code

JS Run

  1. var tree = Ext.create('Ext.tree.Panel', {
  2. renderTo: document.body,
  3. title: 'TreeGrid',
  4. width: 300,
  5. height: 150,
  6. fields: ['name', 'description'],
  7. columns: [{
  8. xtype: 'treecolumn',
  9. text: 'Name',
  10. dataIndex: 'name',
  11. width: 150,
  12. sortable: true
  13. }, {
  14. text: 'Description',
  15. dataIndex: 'description',
  16. flex: 1,
  17. sortable: true
  18. }],
  19. root: {
  20. name: 'Root',
  21. description: 'Root description',
  22. expanded: true,
  23. children: [{
  24. name: 'Child 1',
  25. description: 'Description 1',
  26. leaf: true
  27. }, {
  28. name: 'Child 2',
  29. description: 'Description 2',
  30. leaf: true
  31. }]
  32. }
  33. });

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’.

The fields configuration is passed on to the Ext.data.Model that the internally created Store uses. Notice how the dataIndex configurations on the columns map to the fields we specified - name and description.

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’.

If no defined columns are configured with header text, then the header container will not be shown.

Adding nodes

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

  1. var tree = Ext.create('Ext.tree.Panel');
  2. tree.setRootNode({
  3. text: 'Root',
  4. expanded: true,
  5. children: [{
  6. text: 'Child 1',
  7. leaf: true
  8. }, {
  9. text: 'Child 2',
  10. leaf: true
  11. }]
  12. });

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.

  1. var root = tree.getRootNode();
  2. var parent = root.appendChild({
  3. text: 'Parent 1'
  4. });
  5. parent.appendChild({
  6. text: 'Child 3',
  7. leaf: true
  8. });
  9. parent.expand();

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.

Appending to the tree

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

  1. var parent = root.appendChild({
  2. text: 'Parent 1',
  3. expanded: true,
  4. children: [{
  5. text: 'Child 3',
  6. leaf: true
  7. }]
  8. });

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.

  1. var child = parent.insertChild(0, {
  2. text: 'Child 2.5',
  3. leaf: true
  4. });
  5. parent.insertBefore({
  6. text: 'Child 2.75',
  7. leaf: true
  8. }, child.nextSibling);

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.

Inserting children into the tree

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

Loading and Saving via Proxy

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. This section will explain the intricacies of working with Tree data.

TreeModel Fields

The first and most important thing to understand when working with Tree data is how the TreeModel class’ fields work. Every node in a Tree is simply a Model instance decorated with the TreeModel’s fields and methods. Assume for a moment that an application has a Model called “Person”. A Person only has two fields - “id” and “name”.

In order to use that in a TreeStore, extend the TreeModel class:

  1. Ext.define('Person', {
  2. extend: 'Ext.data.TreeModel',
  3. fields: ['id', {
  4. name: 'name',
  5. type: 'string'
  6. }]
  7. });

The resulting model has many extra fields which are used to manage the node’s context within the tree structure:

  1. console.log(store.getRoot().getFields().length); // outputs '27'

The Person model’s prototype got 25 extra fields added to it just by extending TreeModel.

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

  1. {
  2. name: 'parentId',
  3. type: idType,
  4. defaultValue: null,
  5. useNull: idField.useNull
  6. }, {
  7. name: 'index',
  8. type: 'int',
  9. defaultValue: -1,
  10. persist: false,
  11. convert: null
  12. }, {
  13. name: 'depth',
  14. type: 'int',
  15. defaultValue: 0,
  16. persist: false,
  17. convert: null
  18. }, {
  19. name: 'expanded',
  20. type: 'bool',
  21. defaultValue: false,
  22. persist: false,
  23. convert: null
  24. }, {
  25. name: 'expandable',
  26. type: 'bool',
  27. defaultValue: true,
  28. persist: false,
  29. convert: null
  30. }, {
  31. name: 'checked',
  32. type: 'auto',
  33. defaultValue: null,
  34. persist: false,
  35. convert: null
  36. }, {
  37. name: 'leaf',
  38. type: 'bool',
  39. defaultValue: false
  40. }, {
  41. name: 'cls',
  42. type: 'string',
  43. defaultValue: '',
  44. persist: false,
  45. convert: null
  46. }, {
  47. name: 'iconCls',
  48. type: 'string',
  49. defaultValue: '',
  50. persist: false,
  51. convert: null
  52. }, {
  53. name: 'icon',
  54. type: 'string',
  55. defaultValue: '',
  56. persist: false,
  57. convert: null
  58. }, {
  59. name: 'root',
  60. type: 'boolean',
  61. defaultValue: false,
  62. persist: false,
  63. convert: null
  64. }, {
  65. name: 'isLast',
  66. type: 'boolean',
  67. defaultValue: false,
  68. persist: false,
  69. convert: null
  70. }, {
  71. name: 'isFirst',
  72. type: 'boolean',
  73. defaultValue: false,
  74. persist: false,
  75. convert: null
  76. }, {
  77. name: 'allowDrop',
  78. type: 'boolean',
  79. defaultValue: true,
  80. persist: false,
  81. convert: null
  82. }, {
  83. name: 'allowDrag',
  84. type: 'boolean',
  85. defaultValue: true,
  86. persist: false,
  87. convert: null
  88. }, {
  89. name: 'loaded',
  90. type: 'boolean',
  91. defaultValue: false,
  92. persist: false,
  93. convert: null
  94. }, {
  95. name: 'loading',
  96. type: 'boolean',
  97. defaultValue: false,
  98. persist: false,
  99. convert: null
  100. }, {
  101. name: 'href',
  102. type: 'string',
  103. defaultValue: '',
  104. persist: false,
  105. convert: null
  106. }, {
  107. name: 'hrefTarget',
  108. type: 'string',
  109. defaultValue: '',
  110. persist: false,
  111. convert: null
  112. }, {
  113. name: 'qtip',
  114. type: 'string',
  115. defaultValue: '',
  116. persist: false,
  117. convert: null
  118. }, {
  119. name: 'qtitle',
  120. type: 'string',
  121. defaultValue: '',
  122. persist: false,
  123. convert: null
  124. }, {
  125. name: 'qshowDelay',
  126. type: 'int',
  127. defaultValue: 0,
  128. persist: false,
  129. convert: null
  130. }, {
  131. name: 'children',
  132. type: 'auto',
  133. defaultValue: null,
  134. persist: false,
  135. convert: null
  136. }, {
  137. name: 'visible',
  138. type: 'boolean',
  139. defaultValue: true,
  140. persist: false,
  141. }, {
  142. name: 'text',
  143. type: 'string',
  144. persist: 'false
  145. }

TreeModel Fields are Reserved Names

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” in a Model if that Model is intended to be used in a Tree, since the Model’s field will override the TreeModel field. The exception to this rule is when there is a legitimate need to override the persistence of a field.

Persistent vs Non-persistent Fields

Most of TreeModel’s fields default to persist: false. This means they are non-persistent fields by default. Non-persistent fields will not be saved via the 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 persistence setting, but there are cases where it is necessary to override the persistence of some fields.
The following example demonstrates how to override the persistence of a TreeModel field. When overriding a TreeModel field it is important to only change the persist property. The name, type, and defaultValue properties should never be changed.

  1. // overriding the persistence of TreeModel fields in a Model definition
  2. Ext.define('Person', {
  3. extend: 'Ext.data.TreeModel',
  4. fields: [
  5. // Person fields
  6. { name: 'id', type: 'int' },
  7. { name: 'name', type: 'string' }
  8. // override a non-persistent TreeModel field to make it persistent
  9. { name: 'iconCls', type: 'string', defaultValue: null, persist: true }
  10. ]
  11. });

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

Persistent by default:

  • parentId - used to store the id of a node’s parent node. This field should always be persistent and should not be overridden.
  • leaf - used to indicate that the node is a leaf node and therefore cannot have children appended to it. This field should not normally need to be overridden.

Non-persistent by default:

  • index - used to store the order of nodes within their parent. When a node is inserted or removed, all of its sibling nodes after the insertion or removal point will have their indexes updated. If desired, the application can use this field to persist the ordering of nodes.

    However, if the server uses a different method of storing order, it may be more appropriate to leave the index field as non-persistent. When using a WebStorage Proxy if storing order is required, this field must be overridden to be persistent.

    Also if client-side sorting is being used it is recommended for the index field to be left as non-persistent, since sorting updates the indexes of all the sorted nodes, which would cause them to be persisted on next sync or save if the persist property is true.

  • depth - used to store the depth of a node in the Tree hierarchy. Override this field to turn on persistence if the server needs to store the depth field. When using a WebStorage Proxy it is recommended to not override the persistence of the depth field since it is not needed to properly store the Tree structure and will just take up extra space.

  • checked - this field should be overridden to be persistent if the Tree is using the checkbox feature

  • expanded - used to store the expanded/collapsed state of a node. This field should not normally need to be overridden.
  • expandable - used internally to indicate that this node is expandable. Do not override the persistence of this field.
  • cls - used to apply a CSS class to the node when it is rendered in a TreePanel. Override this field to be persistent if desired.
  • iconCls - used to apply a css class to the node’s icon when it is rendered in a TreePanel. Override this field to be persistent if desired.
  • icon - used to apply a custom icon to the node when it is rendered in a TreePanel. Override this field to be persistent if desired.
  • root - used to indicate that this node is the root node. This field should not be overridden.
  • isLast - used to indicate that this node is the last of its siblings. This field should not normally need to be overridden.
  • isFirst - used to indicate that this node is the first of its siblings. This field should not normally need to be overridden.
  • allowDrop - used internally to deny dropping on the node. Do not override the persistence of this field.
  • allowDrag - used internally to deny dragging the node. Do not override the persistence of this field.
  • loaded - used internally to indicate that the node’s children have been loaded.
    Do not override the persistence of this field.
  • loading - used internally to indicate that the proxy is in the process of loading the node’s children. Do not override the persistence of this field.
  • href - used to specify a url that the node should be a link to. Override to be persistent if desired.
  • hrefTarget - used to specify the target for the href. Override to be persistent if desired.
  • qtip - used to add a tooltip text to the node. Override to be persistent if desired.
  • qtitle - used to specify the title for the tooltip. Override to be persistent if desired.
  • children - used internally when loading a node and its children all in one request. Do not override the persistence of this field.

Loading Data

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

Loading the Entire Tree

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 containing the whole Tree structure. To accomplish this, initialize the TreeStore’s root node to expanded:

  1. Ext.define('Person', {
  2. extend: 'Ext.data.Model',
  3. fields: [
  4. { name: 'id', type: 'int' },
  5. { name: 'name', type: 'string' }
  6. ],
  7. proxy: {
  8. type: 'ajax',
  9. api: {
  10. create: 'createPersons',
  11. read: 'readPersons',
  12. update: 'updatePersons',
  13. destroy: 'destroyPersons'
  14. }
  15. }
  16. });
  17. var store = Ext.create('Ext.data.TreeStore', {
  18. model: 'Person',
  19. root: {
  20. name: 'People',
  21. expanded: true
  22. }
  23. });
  24. Ext.create('Ext.tree.Panel', {
  25. renderTo: document.body,
  26. width: 300,
  27. height: 200,
  28. title: 'People',
  29. store: store,
  30. columns: [{
  31. xtype: 'treecolumn',
  32. header: 'Name',
  33. dataIndex: 'name',
  34. flex: 1
  35. }]
  36. });

Assume that the readPersons url returns the following json object

  1. {
  2. "success": true,
  3. "children": [
  4. { "id": 1, "name": "Phil", "leaf": true },
  5. { "id": 2, "name": "Nico", "expanded": true, "children": [
  6. { "id": 3, "name": "Mitchell", "leaf": true }
  7. ]},
  8. { "id": 4, "name": "Sue", "loaded": true }
  9. ]
  10. }

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

Tree with Bulk Loaded Data

Important items to note:

  • For all non-leaf nodes that do not have children (for example, Person with name Sue above), the server response MUST set the loaded property to true. Otherwise the proxy will attempt to load children for these nodes when they are expanded.
  • The question then arises - if the server is allowed to set the loaded property on a node in the JSON response can it set any of the other non-persistent fields? The answer is yes - sometimes. In the example above, the node with name “Nico” has its expanded field set to true so that it will be initially displayed as expanded in the Tree Panel. Caution should be exercised as there are cases where this is not appropriate and could cause serious problems, like setting the root property on a node that is not the root node for example. In general, loaded and expanded are the only cases where it is recommended for the server to set a non-persistent field in the JSON response.

Dynamically Loading Children

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, that 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. When the node is expanded, the proxy will make another request to the readPersons url that looks something like this:

  1. /readPersons?node=4

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:

  1. {
  2. "success": true,
  3. "children": [
  4. { "id": 5, "name": "Evan", "leaf": true }
  5. ]
  6. }

Now the Tree looks something like this:

Tree with Dynamically Loaded Node

Saving Data

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

Creating a New Node

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

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

  1. newPerson.save();

Updating an Existing Node

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

Removing a Node

  1. store.getRootNode().lastChild.remove();

Bulk Operations

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

  1. store.sync();

Filtering Tree Data

Remote filtering works the same as for any other store type. The filters are encoded and passed to the server which must then respond with only the required data.

Local filtering for trees is different from filtering flat datasets like in grids.

A filter condition may include nodes which are below parent nodes which are excluded by the filter condition.

By default, nodes which pass the filter condition, but who’s parent does not are not included in the store. This is top down filtering, and may be reconfigured using the filterer config.

To force the inclusion of ancestor nodes of nodes which pass the filter, configure filterer as bottomup.

See The Filtered Tree example for an illustration of this type of filtering.

This kind of filtering requires that the tree structure be traversed to ascertain the visibility status of all nodes prior to updating the view.

For fine grained, or programmatic filtering of individual records by application code, you can set the visible field of a TreeModel, and the view will honor that setting and show or hide the node depending on the value.