Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads
Thankful to Krajee!
to get more out of us.

NOTE: This extension depends on the kartik-v/yii2-widget-activeform and creocoder/yii2-nested-sets extensions. Check the composer.json for this extension's requirements and dependencies that may be updated by composer.

An enhanced tree management module from Krajee with inbuilt jQuery plugins and Yii widgets for tree node manipulation and management using nested sets. The module provides ability to manage hierarchical data stored using nested sets. It utilizes the yii2-nested-sets extension to manage the tree structure in your database. Refer the documentation for yii2-nested-sets extension before you start using this module. The yii2-tree-manager module includes two major widgets TreeView and TreeViewInput. In addition, it includes module level settings to easily configure your tree management preferences. It includes a Tree Model which includes inbuilt tree management flags and rules. The model implements and uses a TreeTrait. So one can choose to extend from the Tree Model or implement their own model that uses the TreeTrait. It also includes a NodeController that allows you to manage tree nodes easily via ajax. The tree view widgets and jQuery plugins are built from scratch by Krajee entirely without using any third party plugins. The TreeView is designed using HTML5, jQuery & CSS3 features to work along with the Yii 2 framework.

View a complete demo for TreeView or TreeViewInput.

  • Styled with CSS3, includes jquery transitions and loading sections for ajax content, includes embedded alerts, and utilizes bootstrap css.

  • Tree management feature options and modes:

    • View, edit, and administer the tree structure using TreeView widget as a selector and a form rendered via ajax to edit / manage each tree node

    • Totally extensible through templates and various HTML options and settings available in the widget

    • The form works as both a detail view for the node OR as a management tool to add/edit/delete the node.

    • Form is rendered via ajax. It intelligently uses caching when the same node is clicked again (unless, the nodes are modified).

    • Unique Admin Mode for allowing administrator actions on tree.

    • Includes a configurable toolbar with action buttons for manipulating the treeview

    • Ability to search items in the tree (uses client level search routine for faster performance).

    • Ability to add, edit, or delete tree nodes

    • Ability to reorder tree nodes (move up, down, left or right).

    • Configure tree node icons, labels, styles, and ability to add checkboxes to tree nodes

    • i18N translations enabled across the module.

    • Easily extend or add on your own data elements to the tree structure by extending the Tree model.

  • Bonus: The module also includes a TreeViewInput widget that allows you to use the treeview as an input widget. The TreeViewInput widget is uniquely designed by Krajee (using jQuery, PHP, HTML5 & Bootstrap CSS) to appear as a dropdown selection menu. You can use this widget in two modes:

    • Dropdown Mode: It allows both single and multiple selection (using checkboxes) of node items from the tree and internally stores the node identifiers and displays the name just like a HTML dropdown. The dropdown on expansion automatically displays and uses the treeview for selection of nodes.

    • Inline Mode: Instead of a dropdown to toggle, the entire tree view is directly displayed inline for selection.

  • A separate Tree model specifically built for storing the tree structure, that builds upon the yii2-nested-set model. It includes various prebuilt flags and rules for each tree node, and can be easily extended for various scenarios. Check the Tree Model documentation section for more details.

  • A separate NodeController specifically for tree management. It includes ability to add, view, delete, and move (reorder) nodes using ajax.

The preferred way to install this extension is through composer.

Note

You must read this web tip / wiki on setting the minimum-stability settings for your application's composer.json.

Either run:

$ php composer.phar require kartik-v/yii2-tree-manager "@dev"

or add:

"kartik-v/yii2-tree-manager": "@dev"

to the require section of your composer.json file. Then run:

php composer.phar update

to get the updated package on your application install.

To start using the extension you need to follow certain steps. If you are setting this up manually (not via composer), you need to ensure that the yii2-nested-sets extension is installed. Then follow these steps below to get started:

Create your database table to store the tree structure. Copy and modify the schema/tree.sql file (a MySQL example), to create the table tbl_tree (or for any table name you need). All columns in the table are mandatory. You can add columns if needed to this table, but you cannot skip/drop any of the columns mentioned in the script. You can choose to rename the id, root, lft, rgt, lvl, name, icon, icon_type columns if you choose to - but these must be accordingly setup in the module (refer module section).

You can rename the table if needed. For example, if you have named your tree table as tbl_product, you can set it up as shown below (for MySQL):

CREATE TABLE tbl_product (
    id            INT(11)      NOT NULL AUTO_INCREMENT PRIMARY KEY,
    root          INT(11)               DEFAULT NULL,
    lft           INT(11)      NOT NULL,
    rgt           INT(11)      NOT NULL,
    lvl           SMALLINT(5)  NOT NULL,
    name          VARCHAR(60)  NOT NULL,
    icon          VARCHAR(255)          DEFAULT NULL,
    icon_type     TINYINT(1)   NOT NULL DEFAULT '1',
    active        TINYINT(1)   NOT NULL DEFAULT TRUE,
    selected      TINYINT(1)   NOT NULL DEFAULT FALSE,
    disabled      TINYINT(1)   NOT NULL DEFAULT FALSE,
    readonly      TINYINT(1)   NOT NULL DEFAULT FALSE,
    visible       TINYINT(1)   NOT NULL DEFAULT TRUE,
    collapsed     TINYINT(1)   NOT NULL DEFAULT FALSE,
    movable_u     TINYINT(1)   NOT NULL DEFAULT TRUE,
    movable_d     TINYINT(1)   NOT NULL DEFAULT TRUE,
    movable_l     TINYINT(1)   NOT NULL DEFAULT TRUE,
    movable_r     TINYINT(1)   NOT NULL DEFAULT TRUE,
    removable     TINYINT(1)   NOT NULL DEFAULT TRUE,
    removable_all TINYINT(1)   NOT NULL DEFAULT FALSE,
    KEY tbl_product_NK1 (root),
    KEY tbl_product_NK2 (lft),
    KEY tbl_product_NK3 (rgt),
    KEY tbl_product_NK4 (lvl),
    KEY tbl_product_NK5 (active)
) ENGINE = InnoDB DEFAULT CHARSET = utf8 AUTO_INCREMENT = 1;

Create your model for storing the tree structure extending kartik\tree\models\Tree class. You must configure the tableName method in the model to reflect your correct table name. You can optionally add model rules, or edit the attribute labels. Most importantly, you may wish to edit and override various methods like isVisible, isDisabled etc. to identify allowed flags for nodes. Refer the model section for details.

namespace app\models;

use Yii;

class Product extends \kartik\tree\models\Tree
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_product';
    }    
    
    /**
     * Override isDisabled method if you need as shown in the  
     * example below. You can override similarly other methods
     * like isActive, isMovable etc.
     */
    public function isDisabled()
    {
        if (Yii::$app->user->username !== 'admin') {
            return true;
        }
        return parent::isDisabled();
    }
}

Alternatively, if you do not wish your model Product to extend from \kartik\tree\models\Tree, then you can choose to implement your own model class by using the \kartik\tree\models\TreeTrait as shown below:

namespace app\models;

use Yii;

class Product extends \yii\db\ActiveRecord
{
    use \kartik\tree\models\TreeTrait {
        isDisabled as parentIsDisabled; // note the alias
    }

    /**
     * @var string the classname for the TreeQuery that implements the NestedSetQueryBehavior.
     * If not set this will default to `kartik	ree\models\TreeQuery`.
     */
    public static $treeQueryClass; // change if you need to set your own TreeQuery

    /**
     * @var bool whether to HTML encode the tree node names. Defaults to `true`.
     */
    public $encodeNodeNames = true;

    /**
     * @var bool whether to HTML purify the tree node icon content before saving.
     * Defaults to `true`.
     */
    public $purifyNodeIcons = true;

    /**
     * @var array activation errors for the node
     */
    public $nodeActivationErrors = [];

    /**
     * @var array node removal errors
     */
    public $nodeRemovalErrors = [];

    /**
     * @var bool attribute to cache the `active` state before a model update. Defaults to `true`.
     */
    public $activeOrig = true;
    
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_product';
    }
    
    /**
     * Note overriding isDisabled method is slightly different when
     * using the trait. It uses the alias.
     */
    public function isDisabled()
    {
        if (Yii::$app->user->username !== 'admin') {
            return true;
        }
        return $this->parentIsDisabled();
    }
}

About Tree Node Methods

If you look up at the source of \kartik\tree\models\Tree, you will see few methods starting with is. For example isActive, isDisabled, isMovable etc. You can override these methods for your liking as shown in the example above. Refer the model methods section for details.

Configure the module named treemanager in the modules section of your Yii configuration file. Refer the module section for details.

'modules' => [
   'treemanager' =>  [
        'class' => '\kartik\tree\Module',
        // other module settings, refer detailed documentation
    ]
]

Setup your Yii 2 MVC application and create a controller action to render the TreeView manager. In your view file, you can now use the tree view directly to manage tree data as shown below. Refer the treeview section for details on various settings supported by the widget.

// CONTROLLER - controllers/ProductController.php
class ProductController extends \yii\web\Controller {
    public function actionIndex()
    {
        return $this->render('index');
    }
}

// VIEW - views/product/index.php
use kartik\tree\TreeView;
use app\models\Product;

echo TreeView::widget([
    // single query fetch to render the tree
    // use the Product model you have in the previous step
    'query' => Product::find()->addOrderBy('root, lft'), 
    'headingOptions' => ['label' => 'Categories'],
    'fontAwesome' => false,     // optional
    'isAdmin' => false,         // optional (toggle to enable admin mode)
    'displayValue' => 1,        // initial display value
    'softDelete' => true,       // defaults to true
    'cacheSettings' => [        
        'enableCache' => true   // defaults to true
    ]
]);

Once you have setup the controller and view, you can navigate to the view page containing the TreeView widget. Use the tree view toolbar to create / modify the nodes as highlighted in the figure below. Typically you should start with Create Root Node to create the root node, and then subsequent nodes can be created with Create New Node.

Note

If you wish to pre-create nodes in the database OR want advanced configuration of your tree data, then you can use ActiveRecord methods along with nested set behavior methods to create data. Refer the documentation for yii2-nested-sets for creating / updating nodes via model methods.

If you wish to use the tree input to select tree items, you can use the TreeViewInput widget as shown below. Normally you would use this as a dropdown with the asDropdown property set to true. If asDropdown is set to false, the treeview input widget will be rendered inline for selection. Refer the treeview input section for details.

use kartik\tree\TreeViewInput;
use app\models\Product;

echo TreeViewInput::widget([
    // single query fetch to render the tree
    // use the Product model you have in the previous step
    'query' => Product::find()->addOrderBy('root, lft'), 
    'headingOptions'=>['label'=>'Categories'],
    'name' => 'kv-product', // input name
    'value' => '1,2,3',     // values selected (comma separated for multiple select)
    'asDropdown' => true,   // will render the tree input widget as a dropdown.
    'multiple' => true,     // set to false if you do not need multiple selection
    'fontAwesome' => true,  // render font awesome icons
    'rootOptions' => [
        'label'=>'<i class="fa fa-tree"></i>',  // custom root label
        'class'=>'text-success'
    ], 
    //'options'=>['disabled' => true],
]);

Before using any of the tree management functions, you must add the module to your configuration file. The module must be named treemanager as shown below:

'modules' => [
   'treemanager' =>  [
        'class' => '\kartik\tree\Module',
        // enter other module properties if needed
        // for advanced/personalized configuration
        // (refer module properties available below)
    ]
];

The properties available for the treemanager module are described below:

treeStructure

array, the configuration of nested set attributes structure. You would need to setup the nested set attributes as required in yii2-nested-sets extension. These attributes are mandatory. The treeStructure if not set, defaults to:

[
    'treeAttribute' => 'root',
    'leftAttribute' => 'lft',
    'rightAttribute' => 'rgt',
    'depthAttribute' => 'lvl',
]

treeViewSettings

array, the default settings for the TreeView widget. Refer tree view section for details of the properties supported by the TreeView widget. The following widget properties are very important and are defaulted at the module level if not set.

  • nodeActions: array, the actions for managing, deleting, and moving the tree nodes. The keys must be one of manage, save, remove, and move (highlighted by the Module NODE constants below). The extension already has prebuilt actions defined as part of kartik\tree\controllers\NodeController (refer controller section). The nodeActions defaults to these prebuilt actions:

    'treeViewSettings'=> [
        'nodeActions' => [
            Module::NODE_MANAGE => Url::to(['/treemanager/node/manage']),
            Module::NODE_SAVE => Url::to(['/treemanager/node/save']),
            Module::NODE_REMOVE => Url::to(['/treemanager/node/remove']),
            Module::NODE_MOVE => Url::to(['/treemanager/node/move']),
        ]
    ]
    
  • nodeView: array, the view file that will render the form for managing or editing the tree node. This defaults to:

    'treeViewSettings'=> [
        'nodeView' => '@kvtree/views/_form'
    ]
    

    This view file exists in the views folder of the extension. The view file can read the parameter variable $params, which is an array and returns the following keys:

    • node: kartik\tree\models\Tree, the tree node model

    • modelClass: string, the tree node model class name

    • action: string, the url action to save the node record. This will return basically the nodeActions['save'] setting from the TreeView widget for the saving the node details via ajax.

    • currUrl: string, the current URL for redirecting after save

    • isAdmin: boolean, whether the admin mode is enabled

    • iconsList: array, the dropdown list items for the node icon

    • softDelete: boolean, whether soft delete is enabled for the tree

    • showIDAttribute: boolean, whether the ID key attribute is to be displayed

    • showFormButtons: boolean, whether form action buttons (submit & reset) are to be displayed

    In addition, the $params also returns the following keys from treeStructure and dataStructure:

    • treeAttribute: string, the treeAttribute setting from treeStructure

    • leftAttribute: string, the leftAttribute setting from treeStructure

    • rightAttribute: string, the rightAttribute setting from treeStructure

    • depthAttribute: string, the depthAttribute setting from treeStructure

    • keyAttribute: string, the keyAttribute setting from dataStructure

    • nameAttribute: string, the nameAttribute setting from dataStructure

    • iconAttribute: string, the iconAttribute setting from dataStructure

    • iconTypeAttribute: string, the iconTypeAttribute setting from dataStructure

  • nodeAddlViews: array, the list of additional view files that can be used to embed more content at various sections in the nodeView form. This property is useful to extend the tree view form with more fields and content as needed for your tree node. There are five different view sections where you can embed additional content in the default tree management form.

    • Module::VIEW_PART_1 or 1: beginning part of the form before the default fields (shown to all)

    • Module::VIEW_PART_2 or 2: middle part of the form after the above fields and before ADMIN content (shown to all)

    • Module::VIEW_PART_3 or 3: middle part of the form before the default ADMIN related inputs (shown only to ADMIN)

    • Module::VIEW_PART_4 or 4: middle part of the form after the default ADMIN related inputs (shown only to ADMIN)

    • Module::VIEW_PART_5 or 5: end part of the form after ADMIN content (shown to all)

    Each of the views above will directly receive and can read the same parameters as mentioned in the nodeView section above (e.g. these will be available to the view as $node, $modelClass, $action etc.). In addition, the views will also receive the $form parameter, which is the \kartik\form\ActiveForm instance.

    These views default to empty (which means no content will be rendered in these sections by default). You must provide a valid accessible view file to be rendered (you can use yii path aliases to point to your view file path).

    'treeViewSettings'=> [
        'nodeAddlViews' => [
            Module::VIEW_PART_1 => '',
            Module::VIEW_PART_2 => '',
            Module::VIEW_PART_3 => '',
            Module::VIEW_PART_4 => '',
            Module::VIEW_PART_5 => '',
        ]
    ]
    
    Usage Example Let's say you wish to include an attribute named description to your node management view/form and you wish to display it in VIEW_PART_2 (after the default tree fields and before the admin content). Here's how the view file will look like (let's consider for the example that the view file is located at @frontend/views/site/_treePart2).

    View Configuration

    // @frontend/views/site/_treePart2.php
    echo $form->field($node, 'description')->textArea();
    

    Widget Configuration

    echo kartik\tree\TreeView::widget([
        'query' => Tree::find()->addOrderBy('root, lft'),
        'nodeAddlViews' => [
            Module::VIEW_PART_2 => '@frontend/views/site/_treePart2'
        ]
    ]);
    

unsetAjaxBundles

array, the list of asset bundles that would be unset when rendering the node detail form via ajax (the extension uses the renderAjax method to render the form. This property is important to disallow duplicate registering of asset bundles that would have already been loaded with the main page. If not set, this defaults to the following list of asset bundles:

'unsetAjaxBundles' => [
    'yii\web\YiiAsset',
    'yii\web\JqueryAsset',
    'yii\widgets\ActiveFormAsset',
    'yii\validators\ValidationAsset'
]

i18n

array, the internalization configuration for this module. Defaults to:

'i18n' => [
    'class' => 'yii\i18n\PhpMessageSource',
    'basePath' => '@kvtree/messages',
    'forceTranslation' => true
]

treeEncryptSalt

string, a random salt that will be used to generate a hash signature for tree configuration. If not set, this will be generated using \yii\base\Security::generateRandomKey() to generate a random key. The randomly generated salt will be stored in a session variable identified by Module::SALT_SESS_KEY (i.e. krajeeTreeConfigSalt).

The yii2-tree-manager extension includes two classes for managing the data of your nested sets:

Tree

kartik\tree\models\Tree, the Tree model. The Tree model implements and uses the trait kartik\tree\models\TreeTrait. All your model classes (used for tree structure storage) typically can extend from this class. Alternatively, if you have your model extending from yii\db\ActiveRecord then implement model to use the kartik\tree\models\TreeTrait.

TreeQuery

kartik\tree\models\TreeQuery, the Tree Query class used internally by the Tree model. This class uses Nested Set Query Behavior from yii2-nested-sets. Refer the treeQueryClass property below to override the class name if you choose to build your own tre query class.

The following attributes are available with each tree node model instance but not stored in the database.

treeQueryClass

string, this is a static class property. This identifies the classname for the TreeQuery that implements the NestedSetQueryBehavior. If not set this will default to kartik\tree\models\TreeQuery.

class Product extends kartik\tree\models\Tree {
    public static $treeQueryClass = 'namespace\YourTreeQueryClass'; // if you wish to override this
}

encodeNodeNames

boolean, whether the node name is to be HTML encoded. Defaults to true. To disable it for the entire tree, you can set this property to false in your class that extends the Tree model class. For example:

class Product extends kartik\tree\models\Tree {
    public $encodeNodeNames = false;
}

To modify it for specific model instances - you can set it in your controller OR model methods and validations. For example:

$node = new Product; // your extended Tree model class
$node->encodeNodeNames = true; // set it to true for new records for example

purifyNodeIcons

boolean, whether the node icon is to be HTML purified before saving. Defaults to true. To disable it for the entire tree, you can set this property to false in your class that extends the Tree model class. For example:

class Product extends kartik\tree\models\Tree {
    public $purifyNodeIcons = false;
}

To modify it for specific model instances - you can set it in your controller OR model methods and validations. For example:

$node = new Product; // your extended Tree model class
$node->purifyNodeIcons = true; // set it to true for new records for example

activeOrig

boolean, attribute to cache the active state before a model update. Defaults to true. This is used only internally within the NodeController::save action and should not be normally modified.

Refer the table below, for the details of various database model attributes that are available in the Tree model, and how it can impact each node's behavior in the tree.

attribute type description configurable via module property
id int Unique tree node identifier dataStructure['keyAttribute']
root int Tree root identifier for creating multiple tree roots treeStructure['treeAttribute']
lft int Nested set left property treeStructure['leftAttribute']
rgt int Nested set right property treeStructure['rightAttribute']
lvl int Nested set depth / level property treeStructure['depthAttribute']
name string The tree node name / label dataStructure['nameAttribute']
icon_type int

The icon type to use for the node. Defaults to 1. Can have two values:

  • 1: CSS Class Suffix Name

  • 2: Raw HTML Markup

dataStructure['iconTypeAttribute']
icon string

The node icon. The icon markup is derived based on the following rules:

  • If icon_type is 1, this is treated to be a icon suffix name (for glyphicons or font-awesome depending on the fontAwesome property setting in the TreeView widget).

    For example, to generate a icon markup as <i class="glyphicon glyphicon-book"><i>, you must set this attribute value to just book. Then set fontAwesome property to false in your TreeView widget. If fontAwesome property is true, then <i class="fa fa-book"><i> will be used as the markup for the icon.

  • If icon_type is 2, you can directly set icon to a raw markup using img or your own HTML markup tags.

dataStructure['iconAttribute']

NOTE: If the icon attribute value is null or empty, the icon will be defaulted based on the following rules:

  • Parent nodes will use icon value as folder-close for glyphicons or folder for font-awesome.

  • Child nodes will use icon value as file for both glyphicons and font-awesome.

active boolean Whether the node is active. Defaults to true. When softDelete is set to true in the TreeView widget and then a node is removed / deleted, then the active attribute value will be set to false. If a node is inactive, it will not be visible to normal users and will be visible only when isAdmin is set to true in the TreeView widget. Inactive nodes will be styled differently than active nodes.

- NA -

selected boolean Whether the node is selected by default when the treeview is opened. Defaults to false. This flag can be useful if you are choosing to show checkboxes in your treeview for selecting nodes to do advanced batch / bulk actions.

- NA -

this flag can be controlled only by the admin

disabled boolean Whether the node is disabled. Defaults to false. If a node is disabled, then it cannot be edited OR reordered/moved by normal users. The node can however be set back to enabled by the user, if the isAdmin property is set to true in the TreeView widget. Disabled nodes will be styled differently than enabled nodes.

- NA -

this flag can be controlled only by the admin

readonly boolean Whether the node is readonly. Defaults to false. Its almost similar to disabled, in the fact that the node cannot be edited. However, it may be reordered / moved by normal users. The node can however be set back to not readonly by the user, if the isAdmin property is set to true in the TreeView widget.

- NA -

this flag can be controlled only by the admin

visible boolean Whether the node is visible. Defaults to true. Its slightly different than the active flag, in the sense that a node can be active, but not visible to certain users (refer isVisible method for details). An invisible node can however be set back to not visible by the user, if the isAdmin property is set to true in the TreeView widget.

- NA -

this flag can be controlled only by the admin

collapsed boolean Whether the node is collapsed by default. Defaults to true.

- NA -

this flag can be controlled only by the admin

movable_u boolean Whether the node is movable one position up for the same sibling level in the hierarchy. Defaults to true. Note that the disabled property also controls if a node can be moved.

- NA -

this flag can be controlled only by the admin

movable_d boolean Whether the node is movable one position down for the same sibling level in the hierarchy. Defaults to true. Note that the disabled property also controls if a node can be moved.

- NA -

this flag can be controlled only by the admin

movable_l boolean Whether the node is movable to the left (i.e. from sibling to a parent). Defaults to true. Note that the disabled property also controls if a node can be moved.

- NA -

this flag can be controlled only by the admin

movable_r boolean Whether the node is movable to the right (i.e. from sibling to a child). Defaults to true. Note that the disabled property also controls if a node can be moved.

- NA -

this flag can be controlled only by the admin

removable boolean Whether the node is removable. Defaults to true. This does not remove children below the node. Instead, any children below will be moved as siblings before deletion. Note that the disabled property also controls if a node can be removed. In addition, if softDelete is enabled, the node's active flag will be set to false.

- NA -

this flag can be controlled only by the admin

removable_all boolean Whether the node is removable along with descendants (cascade delete). Defaults to false. Note that the disabled property also controls if a node can be removed. In addition, if softDelete is enabled, the node's active flag will be set to false.

- NA -

this flag can be controlled only by the admin

You can add custom fields to the database table for the Tree model, and set these attributes in your extended Tree model. However NOTE that you must set the model attributes correctly if you need to read & save the custom attribute data via the form. These attributes must be marked as safe in your model rules, else they will not be available for saving via $model->load method for massive assignment.

For example, if you have added a custom field named description in your database table, then you can set the model rules as following:

namespace app\models;
/**
 * This is your extended tree model.
 *
 * @property string $description
 */
class YourTreeModel extends \kartik\tree\models\Tree
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_tree';
    }   

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = parent::rules();
        $rules[] = ['description', 'safe'];
        return $rules;
    }
}

Instead of directly accessing the boolean flags above, the model uses these various methods to get the flag states. These can be overridden when extending the model, to achieve various use cases.

  • isActive(): By default returns the active attribute flag and is used in validating if the node is active.

  • isSelected(): By default returns the selected attribute flag and is used in validating if the node is selected.

  • isDisabled(): By default returns the disabled attribute flag and is used in validating if the node is disabled.

  • isReadonly(): By default returns the readonly attribute flag and is used in validating if the node is readonly.

  • isVisible(): By default returns the visible attribute flag and is used in validating if the node is visible.

  • isCollapsed(): By default returns the collapsed attribute flag and is used in validating if the node is collapsed.

  • isMovable($dir): By default returns if the node is movable up, down, left, or right based on the $dir parameter. The $dir parameter can be one of u, d, l, or r to identify the four movable directions. By default, this method will return the movable_u, movable_d, movable_l, or movable_r attribute values based on the $dir parameter. This method is used in validating if the node is movable in one of the selected directions.

  • isRemovable(): By default returns the removable attribute flag and is used in validating if the node is removable.

  • isRemovableAll(): By default returns the removableAll attribute flag and is used in validating if the node is removable along with descendants.

  • getBreadCrumbs(): generates and returns the breadcrumb title for the node by getting parents upward from the current node. The following parameters can be supplied to this method:

    • depth: int, the breadcrumbs parent depth. Defaults to null, which means infinite depth.

    • glue: string, the pattern to separate the breadcrumbs. Defaults to &raquo; .

    • activeCss: string, the CSS class to be set for current active node. Defaults to kv-crumb-active.

    • untitled: string, the name to be displayed for a new node. Defaults to Untitled.

In addition, the model includes the following additional methods to manipulate nodes:

  • initDefaults(): Initializes default values for each node. Used especially when creating a new node record.

  • activateNode($currNode): Activates a tree node. The activation is recursive with the node's children if removable_all flag is true. This is used specifically for undoing a soft deletion scenario. Consists of a boolean parameter $currNode (default true). If code>$currNode is set to true, it will activate the current parent node in addition to all children below it.

    This method automatically populates a model property nodeActivationErrors, which is an array of items that consists of nodes that faced validation errors in activation. Each item in nodeActivationErrors, consists of the node id, node name, and the node validation error message.

  • removeNode($softDelete, $currNode): Removes a tree node based on the $softDelete boolean parameter. Note if $softDelete is false, the records will be hard deleted from the database. The removal/deactivation process recursive with the node's children if removable_all flag is true. In addition to $softDelete, the method also consists of a boolean parameter $currNode (default true). If code>$currNode is set to true, with $softDelete also set to true, it will deactivate the current parent node in addition to all children below it.

    This method automatically populates a model property nodeRemovalErrors, which is an array of items that consists of nodes that faced validation errors in node removal. Each item in nodeRemovalErrors, consists of the node id, node name, and the node validation error message.

The TreeView is the most important widget that allows tree management and manipulation. You must have setup the database, model, and the treemanager module before you start using the widget. Note that any property setup at the module level within treeViewSettings will be defaulted if you do not set a property here explicitly. You can configure the following properties for the widget:

query

ActiveQuery, the query that will be used as the data source for the TreeView. This property is mandatory. Examples of fetching the entire nested set records in one query fetch is shown below:

// query fetching all tree nodes ordered
Tree::find()->addOrderBy('root, lft');

// query fetching only active tree nodes ordered
Tree::find()->andWhere(['active'=>true])->addOrderBy('root, lft');

displayValue

int, the initial key attribute value to be preselected in the tree view and displayed in the node detail form. Defaults to 1, (the first node identifier).

emptyNodeMsg

string, message shown on tree initialization when either the entire tree is empty or no node is found for the selected displayValue.

emptyNodeMsgOptions

array, array HTML attributes for the empty node message displayed. Defaults to ['class'=>'kv-node-message'].

showIDAttribute

boolean, whether the ID key attribute is to be displayed in the node details form. Defaults to true. If set to false the key attribute will be rendered as a hidden input.

showFormButtons

boolean, whether to show the form action buttons in the node detail form/view. Defaults to true.

breadcrumbs

array, the breadcrumbs settings for displaying the current node title based on parent hierarchy in the node details form/view (starting from the current node). The following settings are supported:

  • depth: int, the depth to dig into the parent nodes for fetching the breadcrumb titles. If set to null or 0 this will fetch breadcrumbs till infinite parent depth. Defaults to null.

  • glue: string, the separator to glue each node name within the breadcrumbs. Defaults to &raquo; .

  • activeCss: string, the CSS class to be applied to the current node name in the breadcrumbs. Defaults to kv-crumb-active.

  • untitled: string, the title to be displayed if this is a new untitled node record. Defaults to Untitled.

nodeFormOptions

array, the HTML attributes for the node detail form. Note that the form ID attribute will be internally generated and cannot be set.

alertFadeDuration

int, the animation duration (ms) for fading in and out alerts that are displayed during manipulation of nodes. Defaults 1000 milliseconds.

nodeLabel

array | Closure, the value to customize a tree node's label..

  • if set as an array, the array key must be the node key value (i.e. keyAttribute) and array value will be the new node label you want to assign.An example configuration using array method to customize the node's label is mentioned below:

    'nodeLabel' => [
        1 => 'Phones Custom', // original name is Phones
        2 => 'Laptops Custom', // original name is Laptops
    ]
    

  • if set as a Closure, the callback function must be of the signature function($node){}, where $node will represent each tree node's model object instance. An example configuration using Closure method to customize the node's label is mentioned below:

    'nodeLabel' => function($node) {
        return $node->name . ' (' . $node->id . ')';
        /**
         * example output(s):
         * 'Phones (1)'
         * 'Laptops (2)'
         */
    }
    

If a value is not traceable through above methods, the default database tree node name will be displayed (as parsed via nameAttribute).

nodeActions

array, optional advanced setup the actions for managing, deleting, and moving the tree nodes. The keys must be one of manage, save, remove, and move (highlighted by the Module NODE constants below). The extension already has prebuilt actions defined as part of NodeController (refer controller section). The nodeActions defaults to these prebuilt actions:

'nodeActions' => [
    Module::NODE_MANAGE => Url::to(['/treemanager/node/manage']),
    Module::NODE_SAVE => Url::to(['/treemanager/node/save']),
    Module::NODE_REMOVE => Url::to(['/treemanager/node/remove']),
    Module::NODE_MOVE => Url::to(['/treemanager/node/move']),
]

nodeView

array, optional advanced setup the view file that will render the form for managing or editing the tree node. This defaults to:

'nodeView' => '@kvtree/views/_form'

This view file exists in the views folder of the extension. The view file can read the parameter variable $params, which is an array and returns the following keys:

  • node: Tree, the tree node model

  • modelClass: string, the tree node model class name

  • action: string, the url action to save the node record. This will return basically the nodeActions['save'] setting from the TreeView widget for the saving the node details via ajax.

  • currUrl: string, the current URL for redirecting after save

  • isAdmin: boolean, whether the admin mode is enabled

  • iconsList: array, the dropdown list items for the node icon

  • softDelete: boolean, whether soft delete is enabled for the tree

  • showFormButtons: boolean, whether form action buttons (submit & reset) are to be displayed

In addition, the $params also returns the following keys from treeStructure and dataStructure:

  • treeAttribute: string, the treeAttribute setting from treeStructure

  • leftAttribute: string, the leftAttribute setting from treeStructure

  • rightAttribute: string, the rightAttribute setting from treeStructure

  • depthAttribute: string, the depthAttribute setting from treeStructure

  • keyAttribute: string, the keyAttribute setting from dataStructure

  • nameAttribute: string, the nameAttribute setting from dataStructure

  • iconAttribute: string, the iconAttribute setting from dataStructure

  • iconTypeAttribute: string, the iconTypeAttribute setting from dataStructure

nodeAddlViews

array, optional advanced setup the list of additional view files that can be used to embed more content at various sections in the nodeView form. This property is useful to extend the tree view form with more fields and content as needed for your tree node. There are five different view sections where you can embed additional content in the default tree management form.


Additional Views Layout

Additional Views Layout


  • Module::VIEW_PART_1 or 1: beginning part of the form before the default fields (shown to all)

  • Module::VIEW_PART_2 or 2: middle part of the form after the above fields and before ADMIN content (shown to all)

  • Module::VIEW_PART_3 or 3: middle part of the form before the default ADMIN related inputs (shown only to ADMIN)

  • Module::VIEW_PART_4 or 4: middle part of the form after the default ADMIN related inputs (shown only to ADMIN)

  • Module::VIEW_PART_5 or 5: end part of the form after ADMIN content (shown to all)

Each of the views above will directly receive and can read the same parameters as mentioned in the nodeView section above (e.g. these will be available to the view as $node, $modelClass, $action etc.). In addition, the views will also receive the $form parameter, which is the ActiveForm instance (from kartik-v/yii2-widget-activeform).

These views default to empty (which means no content will be rendered in these sections).

'nodeAddlViews' => [
    Module::VIEW_PART_1 => '',
    Module::VIEW_PART_2 => '',
    Module::VIEW_PART_3 => '',
    Module::VIEW_PART_4 => '',
    Module::VIEW_PART_5 => '',
]

isAdmin

boolean, whether the tree is to be allowed for editing in admin mode. This will display all nodes (irrespective of their status) and will allow to modify internal tree node flags. If true, it will also display the admin specific configuration flags on the node detail form. Defaults to false.

softDelete

boolean, whether the record will be soft deleted, when remove button is clicked. Defaults to true. The following actions are possible:

  • If true, this will just set the active property of node to false.

  • If false, it will attempt to hard delete the whole record.

showCheckbox

boolean, whether to show a checkbox before each tree node label to allow multiple node selection. Defaults to false.

multiple

boolean, whether to allow multiple selection of checkboxes. Defaults to true. If set to false will not show a checkbox and allow only single selection of tree nodes.

cascadeSelectChildren

boolean, whether to auto select all children when a parent node is selected. Defaults to true. This property will be applied only when the multiple property is set to true.

cacheSettings

array, cache settings for displaying the detail form content for each tree node via ajax. The following options are supported:

  • enableCache: boolean, whether to enable the caching of nodes for the session until a record is updated. Defaults to true.

  • cacheTimeout: int, the cache timeout in milliseconds. Defaults to 300000 (or 5 minutes).

showInactive

boolean, whether to show inactive nodes. Defaults to false.

fontAwesome

boolean, whether to use font awesome icons instead of glyphicons. If set to true, the icon CSS suffix name will be prefixed with fa fa-. Defaults to false.

iconEditSettings

array, settings to edit the icon in the node detail form. You can edit the icon in multiple ways, and can configure this through this property. The following settings are recognized:

  • show: string, whether to display the icons selection as a list. If set to 'text', the icon will be shown as a plain text input along with icon type. If set to 'list', a list will be shown. If set to 'none', then no icon settings will be shown for editing.

  • type: string, the iconTypeAttribute value. Defaults to TreeView::ICON_CSS. Should be one of TreeView::ICON_CSS or TreeView::ICON_RAW.

  • listData: array, the configuration of the icon list data to be shown for selection. This is mandatory if you set show to 'list'. You must set the data as $key => $value format. The list will be parsed to display the icon list and will depend on the type.

    • If type = TreeView::ICON_CSS: $key will be the icon suffix name and $value will be the description for the icon. The icon markup will be automatically parsed then based on whether its a glyphicon or font-awesome, when fontAwesome property is true. For example:

      [
           'folder-close' => 'Folder',
           'file' => 'File',
           'tag' => 'Tag'
      ]
      
    • If type = TreeView::ICON_RAW: $key is the icon HTML markup to be stored and $value will be the description of the icon be displayed as selector in the icon list. For example:

      [
          '<img src="images/folder.jpg">' => 'Folder',
          '<img src="images/file.jpg">' => 'File',
          '<img src="images/tag.jpg">' => 'Tag',
      ]
      

The iconEditSettings defaults to:

[
    'show' => 'text',
    'type' => TreeView::ICON_CSS,
    'listData' => []
]

toolbar

array, the settings for the tree management toolbar. This is setup as $button=>$settings, where $button is one of the toolbar action button (of which you have 8 prebuilt buttons and a button separator). You can choose to edit these prebuilt button settings OR add your own custom buttons and actions beyond these as well.

  • TreeView::BTN_CREATE or 'create': Creates a new tree node.

  • TreeView::BTN_CREATE_ROOT or 'create-root': Creates a new tree root node.

  • TreeView::BTN_REMOVE or 'remove': Removes a tree node.

  • TreeView::BTN_MOVE_UP or 'move-up': Moves the tree node up.

  • TreeView::BTN_MOVE_DOWN or 'move-down': Moves the tree node down.

  • TreeView::BTN_MOVE_LEFT or 'move-left': Moves the tree node left.

  • TreeView::BTN_MOVE_RIGHT or 'move-right': Moves the tree node right.

  • TreeView::BTN_REFRESH or 'refresh': Refreshes the tree by redirecting to current url.

  • TreeView::BTN_SEPARATOR or 'separator': This setting just creates a separator between the buttons in the toolbar.

$setting, array|boolean, is the setting for each button. If you set this property to false, then the button will not be displayed. You can set this as an array having the following keys:

  • icon: the icon CSS suffix name that will be used to render the button icon label using either glyphicons or font-awesome based on the fontAwesome property setting.

  • options: the HTML attributes for the button.

  • url: the URL action that will be called on clicking the button. If this property is set, then the button markup will be automatically converted to a HTML link (i.e. a tag).

The toolbar by default will have the following configuration preset:

[
    TreeView::BTN_CREATE => [
        'icon' => 'plus',
        'options' => ['title' => Yii::t('kvtree', 'Add new'), 'disabled' => true]
    ],
    TreeView::BTN_CREATE_ROOT => [
        'icon' => TreeView::fontAwesome ? 'tree' : 'tree-conifer',
        'options' => ['title' => Yii::t('kvtree', 'Add new root')]
    ],
    TreeView::BTN_REMOVE => [
        'icon' => 'trash',
        'options' => ['title' => Yii::t('kvtree', 'Delete'), 'disabled' => true]
    ],
    TreeView::BTN_SEPARATOR,
    TreeView::BTN_MOVE_UP => [
        'icon' => 'arrow-up',
        'options' => ['title' => Yii::t('kvtree', 'Move Up'), 'disabled' => true]
    ],
    TreeView::BTN_MOVE_DOWN => [
        'icon' => 'arrow-down',
        'options' => ['title' => Yii::t('kvtree', 'Move Down'), 'disabled' => true]
    ],
    TreeView::BTN_MOVE_LEFT => [
        'icon' => 'arrow-left',
        'options' => ['title' => Yii::t('kvtree', 'Move Left'), 'disabled' => true]
    ],
    TreeView::BTN_MOVE_RIGHT => [
        'icon' => 'arrow-right',
        'options' => ['title' => Yii::t('kvtree', 'Move Right'), 'disabled' => true]
    ],
    TreeView::BTN_SEPARATOR,
    TreeView::BTN_REFRESH => [
        'icon' => 'refresh',
        'options' => ['title' => Yii::t('kvtree', 'Refresh')],
        'url' => Yii::$app->request->url
    ],
]

Note

If you notice, the disabled property for most buttons is set to true. The treeview plugin automatically validates and disables or enables the buttons by checking if a valid node record is available for editing.

toolbarOptions

array, the HTML attributes for the toolbar container

buttonGroupOptions

array, the default HTML attributes for the button groups within the toolbar. Defaults to ['class' => 'btn-group-sm'].

buttonOptions

array, the default HTML attributes for the toolbar buttons. Defaults to ['class' => 'btn btn-default']. This will be overridden by the options setting for each button in the toolbar settings.

buttonIconOptions

array, the default HTML attributes for the toolbar button icons. Defaults to [].

showTooltips

boolean, whether to show tooltips for each toolbar button using bootstrap tooltips plugin. Defaults to true.

defaultChildNodeIcon

string, the HTML markup for the icon for a child node, if no icon was setup for the node in the database.

  • Defaults to <i class="glyphicon glyphicon-file"></i>, if fontAwesome is false

  • Defaults to <i class="fa fa-file"></i>, if fontAwesome is true

defaultParentNodeIcon

string, the HTML markup for the icon for a collapsed parent node, if no icon was setup for the node in the database.

  • Defaults to <i class="glyphicon glyphicon-folder-close"></i>, if fontAwesome is false

  • Defaults to <i class="fa fa-folder"></i>, if fontAwesome is true

defaultParentNodeOpenIcon

string, the HTML markup for the icon for an open parent node, if no icon was setup for the node in the database.

  • Defaults to <i class="glyphicon glyphicon-folder-open"></i>, if fontAwesome is false

  • Defaults to <i class="fa fa-folder-open"></i>, if fontAwesome is true

childNodeIconOptions

array, the HTML attributes for the child node icon. Defaults to ['class' => 'text-info']

parentNodeIconOptions

array, the HTML attributes for the child node icon. Defaults to ['class' => 'text-warning']

allowNewRoots

boolean, whether to allow new root node creation. Defaults to true

clientMessages

array, configuration of various client alert messages displayed during node manipulation or editing. Defaults to:

[
    'invalidCreateNode' => Yii::t('kvtree', 'Cannot create node. Parent node is not saved or is invalid.'),
    'emptyNode' => Yii::t('kvtree', '(new)'),
    'removeNode' => Yii::t('kvtree', 'Are you sure you want to remove this node?'),
    'nodeRemoved' => Yii::t('kvtree', 'The node was removed successfully.'),
    'nodeRemoveError' => Yii::t('kvtree', 'Error while removing the node. Please try again later.'),
    'nodeNewMove' => Yii::t('kvtree', 'Cannot move this node as the node details are not saved yet.'),
    'nodeTop' => Yii::t('kvtree', 'Already at top-most node in the hierarchy.'),
    'nodeBottom' => Yii::t('kvtree', 'Already at bottom-most node in the hierarchy.'),
    'nodeLeft' => Yii::t('kvtree', 'Already at left-most node in the hierarchy.'),
    'nodeRight' => Yii::t('kvtree', 'Already at right-most node in the hierarchy.'),
    'emptyNodeRemoved' => Yii::t('kvtree', 'The untitled node was removed.'),
    'selectNode' => Yii::t('kvtree', 'Select a node by clicking on one of the tree items.'),
]

rootOptions

array, the HTML attributes for the topmost root node container. Defaults to ['class' => 'text-primary']. The following special options are recognized

  • label: string, the label for the topmost root node (this is not HTML encoded). Defaults to Root. Set this to empty to not display a label.

rootNodeToggleOptions

array, the HTML attributes for the topmost root node's toggle indicator. Defaults to ['class' => 'text-muted'].

rootNodeCheckboxOptions

array, the HTML attributes for the root node's checkbox indicator. Defaults to ['class' => 'text-success'].

nodeToggleOptions

array, the HTML attributes for the each tree node's toggle indicator. Defaults to ['class' => 'text-muted'].

nodeCheckboxOptions

array, the HTML attributes for the each tree node's checkbox indicator. Defaults to ['class' => 'text-success'].

expandNodeOptions

array, the HTML attributes for the indicator for expanding a node. The following special options are recognized:

  • label: string, the label for the indicator. If not set will default to:

    • Defaults to <i class="glyphicon glyphicon-expand"></i>, if fontAwesome is false

    • Defaults to <i class="fa fa-plus-square-o"></i>, if fontAwesome is true

collapseNodeOptions

array, the HTML attributes for the indicator for collapsing a node. The following special options are recognized:

  • label: string, the label for the indicator. If not set will default to:

    • Defaults to <i class="glyphicon glyphicon-collapse-down"></i>, if fontAwesome is false

    • Defaults to <i class="fa fa-minus-square-o"></i>, if fontAwesome is true

checkedNodeOptions

array, the HTML attributes for the indicator which will represent a checked checkbox The following special options are recognized:

  • label: string, the label for the indicator. If not set will default to:

    • Defaults to <i class="glyphicon glyphicon-checked"></i>, if fontAwesome is false

    • Defaults to <i class="fa fa-check-square-o"></i>, if fontAwesome is true

uncheckedNodeOptions

array, the HTML attributes for the indicator which will represent an unchecked checkbox The following special options are recognized:

  • label: string, the label for the indicator. If not set will default to:

    • Defaults to <i class="glyphicon glyphicon-unchecked"></i>, if fontAwesome is false

    • Defaults to <i class="fa fa-square-o"></i>, if fontAwesome is true

treeWrapperOptions

array, the HTML attributes for the wrapper container for the tree header, body, and footer. Defaults to ['class' => 'kv-tree-wrapper form-control'].

headingOptions

array, the HTML attributes for the tree heading. Defaults to ['class' => 'kv-tree-heading']. The following special options are recognized:

  • label: string, the label for the indicator. If not set will default to:

headerOptions

array, the HTML attributes for the tree header container.

searchContainerOptions

array, the HTML attributes for the tree search container. Defaults to ['class' => 'kv-search-sm'].

searchOptions

array, the HTML attributes for the tree search input control. Defaults to ['class' => 'input-sm'].

searchClearOptions

array, the HTML attributes for the search clear indicator. Defaults to ['class' => 'close'].

footerOptions

array, the HTML attributes for the tree footer container.

treeOptions

array, the HTML attributes for the tree selector container. Defaults to ['style' => 'height:410px'].

detailOptions

array, the HTML attributes for the detail form container which will display the details of the selected node. Defaults to ['style' => 'height:410px'].

options

array, the HTML attributes for the input that will store the selected nodes for the widget. Defaults to ['class' => 'form-control hide'].

krajeeDialogSettings

array, the configuration of Krajee Yii2 Dialog widget that will be used to render the pretty confirmation dialogs and alerts. Refer the Krajee Dialog documentation for details.

mainTemplate

string, the main template for rendering the tree view navigation widget and the node detail view form. Defaults to:

<div class="row">
    <div class="col-sm-3">
        {wrapper}
    </div>
    <div class="col-sm-9">
        {detail}
    </div>
</div>

where:

  • {wrapper} tag indicates the tree view widget container.

  • {detail} tag refers to the node detail form.

wrapperTemplate

string, the wrapper template for rendering the tree view navigation widget. Defaults to:

{header}
{tree}
{footer}

where:

  • {header} tag will generate the tree header.

  • {tree} tag will generate the tree navigation nodes.

  • {footer} tag will generate the tree footer.

headerTemplate

string, the template for rendering the tree header. Defaults to:

<div class="row">
    <div class="col-sm-6">
        {heading}
    </div>
    <div class="col-sm-6">
        {search}
    </div>
</div>

where:

  • {heading} tag will generate the tree heading.

  • {search} tag will generate the tree search control.

footerTemplate

string, the template for rendering the tree footer. Defaults to:

{toolbar}

where:

  • {toolbar} tag will generate the tree toolbar.

View a complete demo for TreeView or TreeViewInput.

The TreeViewInput widget extends from the TreeView widget to allow using the tree view as a selection control and allowing one to select and choose tree nodes into a form input. It allows single and multiple selection of tree nodes. The multiple value input reads, stores and returns the values as a comma separated list of the tree node keys. In addition, to the properties supported by the TreeView widget, the properties for the TreeViewInput widget include the following additions or changes:

  • model: yii\base\Model, the data model that this input widget is associated with.

  • attribute: string, the model attribute that this widget is associated with.

  • name: string, the input name (in case you are not using with model).

  • value: string, the input value (in case you are not using with model). NOTE: The value must be set as comma separated list of keys to be checked and selected in the tree (and not an array).

  • asDropdown: boolean, whether to display the tree view input widget as a dropdown. Defaults to true. If set to false, the tree view input widget will be embedded inline.

  • dropdownConfig: array, the configuration of the tree view dropdown container, when asDropdown is true. The following configuration options are available:

    • input: array, the HTML attributes for the dropdown input container which displays the selected tree items. The following special options are available:

      • placeholder: string, defaults to Select...

    • dropdown: array, the HTML attributes for the dropdown tree view menu.

    • options: array, the HTML attributes for the dropdown wrapper container

    • caret: string, the markup for rendering the dropdown toggle indicator for toggling up and down. Defaults to TreeViewInput::CARET, which is:

      <div class="kv-carets">
          <span class="caret kv-dn"></span>
          <span class="caret kv-up"></span>
      </div>
      
  • options, array, the HTML attributes for the input tag. Defaults to ['class'=>'form-control hide']

Other important properties available from the extension of TreeView widget, and which will impact how your TreeViewInput dropdown will behave are:

  • multiple: boolean, whether to allow multiple selection of checkboxes. Defaults to true. If set to false will not show a checkbox and allow only single selection of tree nodes.

    Note

    When using multiple selection, the input reads and returns data as comma separated values of the selected tree node keys. (the node keys are fetched from id or Module::dataStructure['keyAttribute']) attribute).
  • showToolbar, boolean, this will default to false. Even if you enable it, the only buttons that will be displayed are the reordering (move) buttons.

View a complete demo for TreeView or TreeViewInput.

The NodeController class provides manipulation actions for each tree node. The controller gives access to four important node actions mentioned below.

Note

Setting this is optional. You normally do not need to set or override these CONTROLLER actions UNLESS you need to setup your own custom advanced action for managing nodes. These default node management actions should be directly usable for most use cases.
For advanced cases, where developers need to override these actions, one can point the following settings to their own action in TreeView::nodeActions or at the module level using treeViewSettings['nodeActions'].
  • Module::NODE_MANAGE => /treemanager/node/manage: Action that displays a node for create or update.

  • Module::NODE_SAVE => /treemanager/node/save: Action that saves a changed node.

  • Module::NODE_REMOVE => /treemanager/node/remove: Action that removes a node (deactivates it if TreeView::softDelete is true or deletes it otherwise).

  • Module::NODE_MOVE => /treemanager/node/move: Action that reorders and moves a node in one of the directions up, down, left, or right.

The module has an embedded treeview jQuery plugin designed by Krajee that plays a major role in tree management and control. The plugin triggers jquery events when various management actions are performed on the tree and can be trapped for various advanced use cases. The plugin is automatically initialized on the overall tree container whose HTML element id is identified by TreeView::options['id']. For example, if TreeView::options['id'] = 'treeID', then you can call any plugin event via javascript as shown in the event sections below. The following plugin events are available:

treeview.beforeselect

This event is triggered whenever a tree node is clicked for selection and before the ajax request to load content is sent. Additional parameters available with this event are:

  • key: string|int, the node key identifier (matches the tree node idAttribute value).

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.
  • settings: object, the jquery ajax settings for this transaction.

$("#treeID").on('treeview.beforeselect', function(event, key, jqXHR, settings) {
    console.log('treeview.beforeselect');
});

treeview.selected

This event is triggered whenever a tree node is selected and the ajax content is successfully loaded. Additional parameters available with this event are:

  • key: string|int, the node key identifier (matches the tree node idAttribute value).

  • data: object, the data object sent via server's json response.

  • textStatus: string, the jquery ajax success text status.

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

$("#treeID").on('treeview.selected', function(event, key, data, textStatus, jqXHR) {
    console.log('treeview.selected');
});

treeview.selecterror

This event is triggered whenever a tree node is clicked and an error is received via ajax response. Note that this event is triggered only when the ajax server response will send a json encoded associative array with a key named error to trigger this event. Additional parameters available with this event are:

  • key: string|int, the node key identifier (matches the tree node idAttribute value).

  • data: object, the data object sent via server's json response.

  • textStatus: string, the jquery ajax success text status.

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

$("#treeID").on('treeview.selecterror', function(event, key, data, textStatus, jqXHR) {
    console.log('treeview.selecterror');
});

treeview.selectajaxerror

This event is triggered whenever jquery ajax encounters or throws up an ajax processing exception or error during selection of a node.

  • key: string|int, the node key identifier (matches the tree node idAttribute value).

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

  • textStatus: string, the jquery ajax success text status.

  • errorThrown: string, the jquery ajax error text.

$("#treeID").on('treeview.selectajaxerror', function(event, key, jqXHR, textStatus, errorThrown) {
    console.log('treeview.selectajaxerror');
});

treeview.selectcomplete

This event is triggered on completion of ajax request whenever a tree node is selected. Additional parameters available with this event are:

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

$("#treeID").on('treeview.selectcomplete', function(event, jqXHR) {
    console.log('treeview.selectcomplete');
});

treeview.beforeremove

This event is triggered prior to a tree node delete/removal before the ajax response is sent for delete/removal. Additional parameters available with this event are:

  • key: string|int, the node key identifier (matches the tree node idAttribute value).

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

  • settings: object, the jquery ajax settings for this transaction.

$("#treeID").on('treeview.beforeremove', function(event, key, jqXHR, settings) {
    console.log('treeview.beforeremove');
});

treeview.remove

This event is triggered whenever a tree node is deleted/removed and the ajax delete action is successful. Note that a successful delete success is only determined if the ajax response can send a json encoded associative array with a key named success. Additional parameters available with this event are:

  • key: string|int, the node key identifier (matches the tree node idAttribute value).

  • data: object, the data object sent via server's json response.

  • textStatus: string, the jquery ajax success text status.

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

$("#treeID").on('treeview.remove', function(event, key, data, textStatus, jqXHR) {
    console.log('treeview.remove');
});

treeview.removeerror

This event is triggered whenever a tree node is deleted/removed and an error is received via ajax response. Note that a successful delete success is only determined if the ajax response can send a json encoded associative array with a key named success. Else it will be deemed as a delete error and this event will be triggered. Additional parameters available with this event are:

  • key: string|int, the node key identifier (matches the tree node idAttribute value).

  • data: object, the data object sent via server's json response.

  • textStatus: string, the jquery ajax success text status.

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

$("#treeID").on('treeview.removeerror', function(event, key, data, textStatus, jqXHR) {
    console.log('treeview.removeerror');
});

treeview.removeajaxerror

This event is triggered whenever jquery ajax encounters or throws up an ajax processing exception or error during removal of a node.

  • key: string|int, the node key identifier (matches the tree node idAttribute value).

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

  • textStatus: string, the jquery ajax success text status.

  • errorThrown: string, the jquery ajax error text.

$("#treeID").on('treeview.removeajaxerror', function(event, key, jqXHR, textStatus, errorThrown) {
    console.log('treeview.removeajaxerror');
});

treeview.removecomplete

This event is triggered on completion of ajax request whenever a tree node is removed. Additional parameters available with this event are:

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

$("#treeID").on('treeview.removecomplete', function(event, jqXHR) {
    console.log('treeview.removecomplete');
});

treeview.beforemove

This event is triggered prior to a tree node move (up, down, left, or right) and before the ajax response is sent for reordering/move. Additional parameters available with this event are:

  • dir: string, the direction of move (one of 'u', 'd', 'l', or 'r').

  • keyFrom: string|int, move from node key identifier (matches the tree node idAttribute value).

  • keyTo: string|int, move to node key identifier (matches the tree node idAttribute value).

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

  • settings: object, the jquery ajax settings for this transaction.

$("#treeID").on('treeview.beforemove', function(event, dir, keyFrom, keyTo, jqXHR, settings) {
    console.log('treeview.beforemove');
});

treeview.move

This event is triggered whenever a tree node is moved and the ajax move action is successful. Note that a successful move action is only determined if the ajax response can send a json encoded associative array with a key named success. Additional parameters available with this event are:

  • dir: string, the direction of move (one of 'u', 'd', 'l', or 'r').

  • keyFrom: string|int, move from node key identifier (matches the tree node idAttribute value).

  • keyTo: string|int, move to node key identifier (matches the tree node idAttribute value).

  • data: object, the data object sent via server's json response.

  • textStatus: string, the jquery ajax success text status.

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

$("#treeID").on('treeview.move', function(event, dir, keyFrom, keyTo, data, textStatus, jqXHR) {
    console.log('treeview.move');
});

treeview.moveerror

This event is triggered whenever a tree node is moved and an error is received via ajax response. Note that a successful move action is only determined if the ajax response can send a json encoded associative array with a key named success. Else it will be deemed as a move error and this event will be triggered. Additional parameters available with this event are:

  • dir: string, the direction of move (one of 'u', 'd', 'l', or 'r').

  • keyFrom: string|int, move from node key identifier (matches the tree node idAttribute value).

  • keyTo: string|int, move to node key identifier (matches the tree node idAttribute value).

  • data: object, the data object sent via server's json response.

  • textStatus: string, the jquery ajax success text status.

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

$("#treeID").on('treeview.moveerror', function(event, dir, keyFrom, keyTo, data, textStatus, jqXHR) {
    console.log('treeview.moveerror');
});

treeview.moveajaxerror

This event is triggered whenever jquery ajax encounters or throws up an ajax processing exception or error during moving of a node.

  • dir: string, the direction of move (one of 'u', 'd', 'l', or 'r').

  • keyFrom: string|int, move from node key identifier (matches the tree node idAttribute value).

  • keyTo: string|int, move to node key identifier (matches the tree node idAttribute value).

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

  • textStatus: string, the jquery ajax success text status.

  • errorThrown: string, the jquery ajax error text.

$("#treeID").on('treeview.moveajaxerror', function(event, dir, keyFrom, keyTo, jqXHR, textStatus, errorThrown) {
    console.log('treeview.moveajaxerror');
});

treeview.movecomplete

This event is triggered on completion of ajax request whenever a tree node is moved. Additional parameters available with this event are:

  • jqXHR: XMLHttpRequest, the jQuery XML Http Request object used for this transaction.

$("#treeID").on('treeview.movecomplete', function(event, jqXHR) {
    console.log('treeview.movecomplete');
});

treeview.create

This event is triggered whenever a new node is created under a parent node. This event will not be triggered when a new root node is created. The following additional parameters are available:

  • parent: string|int, the parent node key identifier under which the node will be created (matches the tree node idAttribute value).

$("#treeID").on('treeview.create', function(event, parent) {
    console.log('treeview.create');
});

treeview.createroot

This event is triggered whenever a new root node is created.

$("#treeID").on('treeview.createroot', function(event) {
    console.log('treeview.createroot');
});

treeview.expand

This event is triggered whenever a node is expanded using the tree expand toggle indicator. The following additional parameters are available:

  • nodeKey: string|int, the node key identifier which was expanded (matches the tree node idAttribute value).

$("#treeID").on('treeview.expand', function(event, nodeKey) {
    console.log('treeview.expand');
});

treeview.collapse

This event is triggered whenever a node is collapsed using the tree collapse toggle indicator. The following additional parameters are available:

  • key: string|int, the node key identifier which was expanded (matches the tree node idAttribute value).

$("#treeID").on('treeview.collapse', function(event, key) {
    console.log('treeview.collapse');
});

treeview.expandall

This event is triggered whenever all nodes are expanded using the main root expand toggle indicator.

$("#treeID").on('treeview.expandall', function(event) {
    console.log('treeview.expandall');
});

treeview.collapseall

This event is triggered whenever all nodes are collapsed using the main root collapse toggle indicator.

$("#treeID").on('treeview.collapseall', function(event) {
    console.log('treeview.collapseall');
});

This event is triggered after a search has been performed on the tree nodes using the tree search control.

$("#treeID").on('treeview.search', function(event) {
    console.log('treeview.search');
});

treeview.checked

This event is triggered whenever a node is checked using the tree checkbox selector and is more pertinent when using a TreeViewInput. The following additional parameters are available:

  • key: string|int, the node key identifier which was checked (matches the tree node idAttribute value).

$("#treeID").on('treeview.checked', function(event, key) {
    console.log('treeview.checked');
});

treeview.unchecked

This event is triggered whenever a node is unchecked using the tree checkbox selector and is more pertinent when using a TreeViewInput. The following additional parameters are available:

  • key: string|int, the node key identifier which was unchecked (matches the tree node idAttribute value).

$("#treeID").on('treeview.unchecked', function(event, key) {
    console.log('treeview.unchecked');
});

treeview.change

This event is triggered only for a TreeViewInput whenever a node is changed using the tree checkbox or normal selector (depending on the multiple property setting). The following additional parameters are available:

  • key: string|int, the node key identifier which was unchecked (matches the tree node idAttribute value).

  • name: string, the node name/description which was changed (matches the tree node nameAttribute value).

$("#treeID").on('treeview.change', function(event, key, name) {
    console.log('treeview.change');
});

The embedded treeview jQuery treeview plugin allows access to few important methods for tree node control at runtime via javascript. The plugin is automatically initialized on the overall tree container whose HTML element id is identified by TreeView::options['id']. For example, if TreeView::options['id'] = 'treeID', then you can call any plugin method via javascript as shown in the method sections below. The following methods are available:

expandAll

This method enables you to expand all tree nodes.

$("#treeID").treeview("expandAll");

collapseAll

This method enables you to collapse all tree nodes.

$("#treeID").treeview("collapseAll");

checkAll

This method enables you to check all tree nodes (especially when using a TreeViewInput).

$("#treeID").treeview("checkAll");

uncheckAll

This method enables you to uncheck all tree nodes (especially when using a TreeViewInput).

$("#treeID").treeview("uncheckAll");

checkNode

This method enables you to check a specific tree node (especially when using a TreeViewInput). Additional parameters available with this method are:

  • key: string|int, the node key identifier to be checked (matches the tree node idAttribute value).

$("#treeID").treeview("checkNode", "7"); // checks node key = "7"

uncheckNode

This method enables you to uncheck a specific tree node (especially when using a TreeViewInput). Additional parameters available with this method are:

  • key: string|int, the node key identifier to be unchecked (matches the tree node idAttribute value).

$("#treeID").treeview("uncheckNode", "7"); // unchecks node key = "7"

yii2-tree-manager is released under the BSD 3-Clause License. See the bundled LICENSE.md for details.