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.
Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)
TreeView
supports configuration of the bootstrap library version so that you can use this either with any Bootstrap version 3.x and above. For setting up the bootstrap version for your extension, you can configure the TreeView::bsVersion
property to one of the following.
To use with bootstrap 3 library - you can set TreeView::bsVersion
property to any string starting with 3 (e.g. 3
or 3.3.7
or 3.x
)
To use with bootstrap 4 library - you can set TreeView::bsVersion
property to any string starting with 4 (e.g. 4
or 4.6.0
or 4.x
)
To use with bootstrap 5 library - you can set TreeView::bsVersion
property to any string starting with 5 (e.g. 5
or 5.1.0
or 5.x
)
Generally, you may also want to set a default version globally for all Krajee Extensions (instead of setting it for each widget or extension separately). In order to do this, you can setup the bsVersion
property within Yii 2 application params (i.e. Yii::$app->params['bsVersion']
). To set this up, add this section of code to your application params configuration file (e.g. config/params.php
):
'params' => [ 'bsVersion' => '5.x', // this will set globally `bsVersion` to Bootstrap 5.x for all Krajee Extensions // other settings // 'adminEmail' => 'admin@example.com' ]
If TreeView::bsVersion
property is set, in addition to Yii::$app->params['bsVersion']
, the extension level setting (TreeView::bsVersion
property) will override the Yii::$app->params['bsVersion']
. If TreeView::bsVersion
property is not set, and Yii::$app->params['bsVersion']
is also not set, TreeView::bsVersion
property will default to 3.x
(i.e. Bootstrap 3.x version will be assumed as default).
You need to install one of yiisoft/yii2-bootstrap
or yiisoft/yii2-bootstrap4
or yiisoft/yii2-bootstrap5
extensions manually in your application to enable Bootstrap 3.x or 4.x or 5.x functionality respectively. This dependency has not been pre-built into the composer configuration for Krajee extensions, to allow better control to the developers in configuring their bootstrap library version. If bsVersion
is set to 5.x
and yiisoft/yii2-bootstrap5
is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap5
extension. If bsVersion
is set to 4.x
and yiisoft/yii2-bootstrap4
is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap4
extension. Similarly, if bsVersion
is set to 3.x
and yiisoft/yii2-bootstrap
is not installed, an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap
extension.
To install yiisoft/yii2-bootstrap5
, add the repo to the require
section of your application's composer.json.
"yiisoft/yii2-bootstrap5": "@dev"
To install yiisoft/yii2-bootstrap4
, add the repo to the require
section of your application's composer.json.
"yiisoft/yii2-bootstrap4": "@dev"
To install yiisoft/yii2-bootstrap
, add the repo to the require
section of your application's composer.json.
"yiisoft/yii2-bootstrap": "@dev"
The Krajee extension asset bundle(s) by default depend on one of the following asset bundles to load the Bootstrap CSS and JS:
yii\bootstrap\BootstrapAsset
and/or yii\bootstrap\BootstrapPluginAsset
for bootstrap 3.x (bsVersion = 3
setting)
yii\bootstrap4\BootstrapAsset
and/or yii\bootstrap4\BootstrapPluginAsset
for bootstrap 4.x ( bsVersion = 4
setting)
yii\bootstrap5\BootstrapAsset
and/or yii\bootstrap5\BootstrapPluginAsset
for bootstrap 5.x (bsVersion = 5
setting)
This is controlled by the property bsDependencyEnabled
within the asset bundle (which defaults to true
). One can override this and prevent the default yii2 bootstrap assets (CSS & JS) from loading by doing one or all of the following:
Global Override: Set Yii::$app->params['bsDependencyEnabled']
to false
in your Yii 2 application config params.php
. This setting will be applied for all Krajee Extension Asset Bundles that depend on Bootstrap assets.
'params' => [ 'bsDependencyEnabled' => false, // this will not load Bootstrap CSS and JS for all Krajee extensions // you need to ensure you load the Bootstrap CSS/JS manually in your view layout before Krajee CSS/JS assets // // other params settings below // 'bsVersion' => '5.x', // 'adminEmail' => 'admin@example.com' ]
Asset Bundle Specific Override: Set bsDependencyEnabled
to false
for the specific asset bundle within Yii2 Asset Manager component in your Yii 2 application config file.
// ... 'components' => [ 'assetManager' => [ 'bundles' => [ 'kartik\form\ActiveFormAsset' => [ 'bsDependencyEnabled' => false // do not load bootstrap assets for a specific asset bundle ], ], ], ],
When setting bsDependencyEnabled
to false
, you need to ensure that your app code/view layout loads the Bootstrap CSS and JS on your view before the Krajee CSS/JS are loaded to ensure that the Krajee extension JS plugins and CSS styles do not get broken.
Bootstrap 5.x / 4.x does not include glyphicons or any other icons framework bundled with the library. Krajee extensions therefore will use Font Awesome 5.x icons instead of glyphicons when working with Bootstrap 5.x / 4.x. You can download Font Awesome 5.x icons from the icons website. Alternatively, you can load the free version of Font Awesome from their CDN.
For Krajee extensions and demos, the Font Awesome Free version is used and loaded as the Icons Display Package on all the Yii2 demo layouts. To include font awesome assets on your page, include the following markup on the HEAD
section of your view layout file, when bsVersion
is set to 4.x
or 5.x
.
Option 1: Font CSS version of Font Awesome:
<!-- on your view layout file HEAD section --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
Option 2: SVG / JS version of Font Awesome (recommended for cleaner scaling vector icons and features like icon layers):
<!-- on your view layout file HEAD section --> <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" crossorigin="anonymous"></script>
Alternatively, you can use the FontAwesomeAsset
from the kartik-v/yii2-icons
package to load the SVG/JS version.
// on your view layout file use kartik\icons\FontAwesomeAsset; FontAwesomeAsset::register($this);
The yii2-tree-manager
extension can be installed automatically or manually using one of these options:
Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-tree-manager
via composer
package manager. Either run:
$ php composer.phar require kartik-v/yii2-tree-manager "dev-master"
or add:
"kartik-v/yii2-tree-manager": "dev-master"
to your application's composer.json
file.
You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.
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:
You can run the migrations script provided in the extension migration folder to create the database structure. For this you need to run the migration script from your yii programming console:
php yii migrate/up --migrationPath=@vendor/kartik-v/yii2-tree-manager/src/migrations
Alternatively, you can execute the SQL script to generate your tree database 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, child_allowed 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 common\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 common\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(); } }
\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.
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:
To use with Bootstrap library - you can set this to any string starting with
3
(e.g. 3
or 3.3.7
or 4.x / 3.x
)
To use with bootstrap 4 - you can set this to any string starting with
4
(e.g. 4
or 4.6.0
or 4.x
)
To use with bootstrap 5 - you can set this to any string starting with
4
(e.g. 5
or 5.1.0
or 5.x
)
array, the bootstrap grid column css prefixes mapping, the key is the bootstrap versions, and the value is an array containing the sizes and their corresponding grid column css prefixes. The class using this trait, must implement kartik\base\BootstrapInterface
. If not set will default to:.
[ 3 => [ self::SIZE_X_SMALL => 'col-xs-', self::SIZE_SMALL => 'col-sm-', self::SIZE_MEDIUM => 'col-md-', self::SIZE_LARGE => 'col-lg-', self::SIZE_X_LARGE => 'col-lg-', self::SIZE_XX_LARGE => 'col-lg-', ], 4 => [ self::SIZE_X_SMALL => 'col-', self::SIZE_SMALL => 'col-sm-', self::SIZE_MEDIUM => 'col-md-', self::SIZE_LARGE => 'col-lg-', self::SIZE_X_LARGE => 'col-xl-', self::SIZE_XX_LARGE => 'col-xl-', ], 5 => [ self::SIZE_X_SMALL => 'col-', self::SIZE_SMALL => 'col-sm-', self::SIZE_MEDIUM => 'col-md-', self::SIZE_LARGE => 'col-lg-', self::SIZE_X_LARGE => 'col-xl-', self::SIZE_XX_LARGE => 'col-xxl-', ], ];
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', ]
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 has access to the following parameter variables:
node
: kartik\tree\models\Tree, the tree node model
modelClass
: string, the tree node model class name
isAdmin
: boolean, the isAdmin setting from TreeView widget
softDelete
: boolean, the softDelete setting from TreeView widget
showIDAttribute
: boolean, the showIDAttribute setting from TreeView widget
showFormButtons
: boolean, the showFormButtons setting from TreeView widget
allowNewRoots
: boolean, the allowNewRoots setting from TreeView widget
iconsList
: array, the generated dropdown list items for the node icon configuration.
currUrl
: string, the current URL for redirecting after save
formAction
: string|array, the route / action for saving the node detail form. This will
return basically the nodeActions['save']
setting within nodeActions from the TreeView widget for
the saving the node details. Defaults to current controller action if not set.
formOptions
: array, the HTML attributes for the node detail form.
breadcrumbs
: array, the breadcrumbs setting from TreeView widget.
nodeAddlViews
: array, the nodeAddlViews setting from TreeView widget.
nodeViewButtonLabels
: array, the nodeViewButtonLabels setting from TreeView widget.
nodeViewParams
: string, the PHP serialized string for the nodeViewParams setting from TreeView widget.
nodeSelected
: string|int, the primary key identifier value for the current selected node.
defaultBtnCss
: string, the default CSS class to be appended for the buttons in the node view.
noNodesMessage
: string, the HTML message markup to be displayed when an empty node is found .
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
nodeViewButtonLabels
: array, the labels for the submit and reset buttons displayed in the node view form.
Defaults to the following setting:
[ 'submit' => '<i class="fas fa-floppy-disk"></i>', 'reset' => ' <i class="fas fa-repeat"></i>' ]
nodeViewParams
: array, the additional parameters that can be passed to the node view as key => value
pairs. This property is useful when you are rendering your own custom nodeView
.
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 => '', ] ]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
).
// @frontend/views/site/_treePart2.php echo $form->field($node, 'description')->textArea();
echo kartik\tree\TreeView::widget([ 'query' => Tree::find()->addOrderBy('root, lft'), 'nodeAddlViews' => [ Module::VIEW_PART_2 => '@frontend/views/site/_treePart2' ] ]);
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' ]
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
.
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.
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 }
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
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
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
|
dataStructure['iconTypeAttribute'] |
icon |
string | The node icon. The icon markup is derived based on the following rules:
|
dataStructure['iconAttribute'] NOTE: If the icon attribute value is null or empty, the icon will be defaulted based on the following rules:
|
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 |
child_allowed |
boolean | Whether children nodes are allowed be added / created for the selected node. Defaults to true .
|
- 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 common\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.
isChildAllowed()
: By default returns the child_allowed
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 »
.
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.
To use with Bootstrap library - you can set this to any string starting with
3
(e.g. 3
or 3.3.7
or 4.x / 3.x
)
To use with bootstrap 4 - you can set this to any string starting with
4
(e.g. 4
or 4.6.0
or 4.x
)
To use with bootstrap 5 - you can set this to any string starting with
4
(e.g. 5
or 5.1.0
or 5.x
)
array, the bootstrap grid column css prefixes mapping, the key is the bootstrap versions, and the value is an array containing the sizes and their corresponding grid column css prefixes. The class using this trait, must implement kartik\base\BootstrapInterface
. If not set will default to:.
[ 3 => [ self::SIZE_X_SMALL => 'col-xs-', self::SIZE_SMALL => 'col-sm-', self::SIZE_MEDIUM => 'col-md-', self::SIZE_LARGE => 'col-lg-', self::SIZE_X_LARGE => 'col-lg-', self::SIZE_XX_LARGE => 'col-lg-', ], 4 => [ self::SIZE_X_SMALL => 'col-', self::SIZE_SMALL => 'col-sm-', self::SIZE_MEDIUM => 'col-md-', self::SIZE_LARGE => 'col-lg-', self::SIZE_X_LARGE => 'col-xl-', self::SIZE_XX_LARGE => 'col-xl-', ], 5 => [ self::SIZE_X_SMALL => 'col-', self::SIZE_SMALL => 'col-sm-', self::SIZE_MEDIUM => 'col-md-', self::SIZE_LARGE => 'col-lg-', self::SIZE_X_LARGE => 'col-xl-', self::SIZE_XX_LARGE => 'col-xxl-', ], ];
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:
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');
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).
string, message shown on tree initialization when either the entire
tree is empty or no node is found for the selected displayValue
.
array, array HTML attributes for the empty node message displayed. Defaults to ['class'=>'kv-node-message']
.
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.
boolean, whether to show the form action buttons in the node detail form/view. Defaults to true
.
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 »
.
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
.
array, the HTML attributes for the node detail form. Note that the form ID attribute will be internally generated and cannot be set.
int, the animation duration (ms) for fading in and out alerts that are displayed during manipulation of nodes. Defaults 1000
milliseconds.
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
).
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']), ]
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 has access to the following parameter variables:
node
: kartik\tree\models\Tree, the tree node model
modelClass
: string, the tree node model class name
isAdmin
: boolean, the isAdmin setting from TreeView widget
softDelete
: boolean, the softDelete setting from TreeView widget
showIDAttribute
: boolean, the showIDAttribute setting from TreeView widget
showFormButtons
: boolean, the showFormButtons setting from TreeView widget
allowNewRoots
: boolean, the allowNewRoots setting from TreeView widget
iconsList
: array, the generated dropdown list items for the node icon configuration.
currUrl
: string, the current URL for redirecting after save
formAction
: string|array, the route / action for saving the node detail form. This will
return basically the nodeActions['save']
setting within nodeActions from the TreeView widget for
the saving the node details. Defaults to current controller action if not set.
formOptions
: array, the HTML attributes for the node detail form.
breadcrumbs
: array, the breadcrumbs setting from TreeView widget.
nodeAddlViews
: array, the nodeAddlViews setting from TreeView widget.
nodeViewButtonLabels
: array, the nodeViewButtonLabels setting from TreeView widget.
nodeViewParams
: string, the PHP serialized string for the nodeViewParams setting from TreeView widget.
nodeSelected
: string|int, the primary key identifier value for the current selected node.
defaultBtnCss
: string, the default CSS class to be appended for the buttons in the node view.
noNodesMessage
: string, the HTML message markup to be displayed when an empty node is found .
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
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
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 => '', ]
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
.
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.
boolean, whether to show a checkbox before each tree node label to allow
multiple node selection. Defaults to false
.
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.
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
.
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)
.
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
.
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 the fontAwesome setting from TreeView widget 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' => [] ]
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
: string, the icon CSS suffix name that will be used to render the button icon label using either glyphicons or font-awesome based on the the fontAwesome setting from TreeView widget property setting.
alwaysDisabled
: boolean, whether the button will always be disabled. Defaults to false
. If this is set to true
, it will override other settings (e.g. options['disabled']
) and also will not be automatically enabled based on the selected tree node config. If this property is set to true
on a button having the url
setting, then it will be rendered as a disabled button markup and the url setting stored in a data attribute named data-url
.
options
: array, the HTML attributes for the button.
url
: string|array, 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', 'alwaysDisabled' => false, 'options' => ['title' => Yii::t('kvtree', 'Add new'), 'disabled' => true] ], TreeView::BTN_CREATE_ROOT => [ 'icon' => TreeView::fontAwesome ? 'tree' : 'tree-conifer', 'alwaysDisabled' => false, 'options' => ['title' => Yii::t('kvtree', 'Add new root')] ], TreeView::BTN_REMOVE => [ 'icon' => 'trash', 'alwaysDisabled' => false, 'options' => ['title' => Yii::t('kvtree', 'Delete'), 'disabled' => true] ], TreeView::BTN_SEPARATOR, TreeView::BTN_MOVE_UP => [ 'icon' => 'arrow-up', 'alwaysDisabled' => false, 'options' => ['title' => Yii::t('kvtree', 'Move Up'), 'disabled' => true] ], TreeView::BTN_MOVE_DOWN => [ 'icon' => 'arrow-down', 'alwaysDisabled' => false, 'options' => ['title' => Yii::t('kvtree', 'Move Down'), 'disabled' => true] ], TreeView::BTN_MOVE_LEFT => [ 'icon' => 'arrow-left', 'alwaysDisabled' => false, 'options' => ['title' => Yii::t('kvtree', 'Move Left'), 'disabled' => true] ], TreeView::BTN_MOVE_RIGHT => [ 'icon' => 'arrow-right', 'alwaysDisabled' => false, 'options' => ['title' => Yii::t('kvtree', 'Move Right'), 'disabled' => true] ], TreeView::BTN_SEPARATOR, TreeView::BTN_REFRESH => [ 'icon' => 'refresh', 'alwaysDisabled' => false, 'options' => ['title' => Yii::t('kvtree', 'Refresh')], 'url' => Yii::$app->request->url ], ]
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.
array, the default HTML attributes for the button groups within the toolbar. Defaults to ['class' => 'btn-group-sm']
.
array, the default HTML attributes for the toolbar buttons. Defaults to ['class' => 'btn btn-secondary btn-default']
. This will be overridden by the options
setting for each button in the toolbar settings.
boolean, whether to show tooltips for each toolbar button using bootstrap tooltips plugin. Defaults to true
.
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="fas fa-file"></i>
, if the fontAwesome setting from TreeView widget is false
Defaults to <i class="fa fa-file"></i>
, if the fontAwesome setting from TreeView widget is true
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="fas fa-folder-close"></i>
, if the fontAwesome setting from TreeView widget is false
Defaults to <i class="fa fa-folder"></i>
, if the fontAwesome setting from TreeView widget is true
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="fas fa-folder-open"></i>
, if the fontAwesome setting from TreeView widget is false
Defaults to <i class="fa fa-folder-open"></i>
, if the fontAwesome setting from TreeView widget is true
array, the HTML attributes for the child node icon. Defaults to ['class' => 'text-info']
array, the HTML attributes for the child node icon. Defaults to ['class' => 'text-warning']
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.'), ]
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.
array, the HTML attributes for the topmost root node's toggle indicator.
Defaults to ['class' => 'text-muted']
.
array, the HTML attributes for the root node's checkbox indicator.
Defaults to ['class' => 'text-success']
.
array, the HTML attributes for the each tree node's toggle indicator.
Defaults to ['class' => 'text-muted']
.
array, the HTML attributes for the each tree node's checkbox indicator.
Defaults to ['class' => 'text-success']
.
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="fas fa-expand"></i>
, if the fontAwesome setting from TreeView widget is false
Defaults to <i class="fa fa-plus-square-o"></i>
, if the fontAwesome setting from TreeView widget is true
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="fas fa-collapse-down"></i>
, if the fontAwesome setting from TreeView widget is false
Defaults to <i class="fa fa-minus-square-o"></i>
, if the fontAwesome setting from TreeView widget is true
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="fas fa-checked"></i>
, if the fontAwesome setting from TreeView widget is false
Defaults to <i class="fa fa-check-square-o"></i>
, if the fontAwesome setting from TreeView widget is true
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="fas fa-unchecked"></i>
, if the fontAwesome setting from TreeView widget is false
Defaults to <i class="fa fa-square-o"></i>
, if the fontAwesome setting from TreeView widget is true
array, the HTML attributes for the wrapper container for the tree header, body, and footer.
Defaults to ['class' => 'kv-tree-wrapper form-control']
.
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:
boolean, whether to hide unmatched search items in the search results when searching the tree. Defaults to true
.
array, the HTML attributes for the tree search container.
Defaults to ['class' => 'kv-search-sm']
.
array, the HTML attributes for the tree search input control.
Defaults to ['class' => 'input-sm']
.
array, the HTML attributes for the search clear indicator. Defaults to ['class' => 'close']
.
array, the HTML attributes for the tree selector container.
Defaults to ['style' => 'height:410px']
.
array, the HTML attributes for the detail form container which will
display the details of the selected node. Defaults to ['style' => 'height:410px']
.
array, the HTML attributes for the input that will store the
selected nodes for the widget. Defaults to ['class' => 'form-control hide']
.
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.
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.
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.
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.
string, the template for rendering the tree footer. Defaults to:
{toolbar}
where:
{toolbar}
tag will generate the tree toolbar.
string, the icon prefix string to be prepended before the icon CSS. If not set it will default to one of the following:
"fas fa-"
when the bsVersion setting from TreeView widget is set to 3.x
and the the fontAwesome setting from TreeView widget property is set to false
.
"fa fa-"
when the bsVersion setting from TreeView widget is set to 3.x
and the the fontAwesome setting from TreeView widget property is set to true
.
"fas fa-"
: when the bsVersion setting from TreeView widget is set to 4.x
. Note that the the fontAwesome setting from TreeView widget property has no impact when using bootstrap 4.x
.
View a complete demo for TreeView or TreeViewInput.
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.
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.
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:
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|integer, 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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
This event is triggered whenever a new root node is created.
$("#treeID").on('treeview:createroot', function(event) { console.log('treeview:createroot'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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'); });
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:
This method enables you to expand all tree nodes.
$("#treeID").treeview("expandAll");
This method enables you to collapse all tree nodes.
$("#treeID").treeview("collapseAll");
This method enables you to check all tree nodes (especially when using a TreeViewInput).
$("#treeID").treeview("checkAll");
This method enables you to uncheck all tree nodes (especially when using a TreeViewInput).
$("#treeID").treeview("uncheckAll");
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"
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.
Comments & Discussion
Note
You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.
The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.