How to pass node id for each node clicked in kartik treeview?

社会主义新天地 提交于 2020-07-03 13:08:54

问题


I have multiple nodes. I want to show different views on each node click. For this, I have to pass the node id. Below is my code in which I have tried to explain the total scenario

`<?=
    TreeView::widget([
        'query' => \common\models\MdcNode::find()->addOrderBy('root, lft'),
        'headingOptions' => ['label' => 'Root'],
        'rootOptions' => ['label'=>'<span class="text-primary">Root</span>'],
        'topRootAsHeading' => true, // this will override the headingOptions
        //'displayValue' => 1,        // initial display value
        'isAdmin' => false,
        'fontAwesome' => true,
        //'nodeView' => '',
        //show => none removes the iconType etc setting under details
        'iconEditSettings'=>['show'=>'none'],

        'toolbar' =>
            [
            TreeView::BTN_REFRESH => false,
            TreeView::BTN_CREATE => false,
            TreeView::BTN_CREATE_ROOT => false,
            TreeView::BTN_REMOVE => false,
            TreeView::BTN_SEPARATOR => false,
            TreeView::BTN_MOVE_UP => false,
            TreeView::BTN_MOVE_DOWN => false,
            TreeView::BTN_MOVE_LEFT => false,
            TreeView::BTN_MOVE_RIGHT => false,
        ],

        'showIDAttribute' => false,
        'showTooltips' => false,

        'showNameAttribute' => false,
        'softDelete' => false,
        'cacheSettings' => ['enableCache' => true],
        //removing the detail below removes the second column of view(s) 1 - 5. Section 5 is being used to render the extra data. See frontend\config\main.php later.
        'mainTemplate'=>'<div class="row">
                        <div class="col-sm-3">
                            {wrapper}
                        </div>
                        <div class="col-sm-9">
                            {detail}
                        </div>
                     </div>',
        'nodeAddlViews' => [
            Module::VIEW_PART_1 => '',
            Module::VIEW_PART_2 => '',
            Module::VIEW_PART_3 => '',
            Module::VIEW_PART_4 => '',
            Module::VIEW_PART_5 => '@backend/views/api/index',
        ]

    ]);
    ?>`

Controller

public function actionIndex() { echo "{Index}"; }

View

<?PHP
  /* @var $this yii\web\View */
  ?>
  

  <p>
    You may change the content of this page by modifying
    the file <code><?= __FILE__; ?></code>.
  </p>

UI

image

How can I pass each node id to my view when I click each node? Any help would be highly appreciated.


回答1:


Using this answer for support in your node view ie. nodeAddlView located in your Treeview widget under the variable nodeAddlView or in your TreeViewSettings array with nodeAddlView located in your config/main.php you have an alias eg. @app which is the default for the advanced app and ie. not listed under common/config/bootstrap.php eg.

<?php
Yii::setAlias('@common', dirname(__DIR__));
Yii::setAlias('@frontend', dirname(dirname(__DIR__)) . '/frontend');
Yii::setAlias('@bower', dirname(dirname(__DIR__)) . '/vendor/bower-asset');
Yii::setAlias('@migrations', dirname(dirname(__DIR__)) . '/frontend/migrations');
Yii::setAlias('@console', dirname(dirname(__DIR__)) . '/console');

and is not listed with the 'aliases' setting under frontend/config/main.php here:

'aliases'=>[
      '@bower'=>'@vendor/bower-asset',
      '@npm'=>'@vendor/npm-asset',
    ],

This alias is joined or concatenated with a path. This combination sits under Module in the frontend/config/main.php. eg.

'treemanager' =>  [
        'class' => 'kartik\tree\Module',
        'treeViewSettings'=> [
            'nodeView' => '@kvtree/views/_form',    
            'nodeAddlViews' => [
                1 => '',
                2 => '',
                3 => '',
                4 => '',
                5 => '@app/views/krajeeproducttree/product',
        ]]    
       ],

or in the Treeview::widget parameters eg.

<?php  
    echo TreeView::widget([
        // single query fetch to render the tree
        'query' => KrajeeProductTree::find()->addOrderBy('root, lft'),
        'nodeView' => '@kvtree/views/_form',    
        'nodeAddlViews' => [
            1 => '',
            2 => '',
            3 => '',
            4 => '',
            5 => '@app/views/krajeeproducttree/product',
         ],  
        'headingOptions' => ['label' => 'Categories'],
        'fontAwesome' => true,      // 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
        ],
        'hideTopRoot'=>true,
        'treeOptions' => ['style' => 'height:1000px width:900px' ],
        //more detail can be added to the node here eg. $node->id but
        //for security better adding it to the bottom of your
        // view file listed here 
        // eg.   5 => '@app/views/krajeeproducttree/product', 
        // since it automatically carries and is passed the $node variable.
        'nodeLabel' => function($node) {
                             return $node->name . " ". $node->id;
                       },
        //disable the toolbar completely                       
        'toolbar'           => [
                TreeView::BTN_REFRESH => false,
                TreeView::BTN_CREATE => false,
                TreeView::BTN_CREATE_ROOT => false,
                TreeView::BTN_REMOVE => false,
                TreeView::BTN_SEPARATOR => false,
                TreeView::BTN_MOVE_UP => false,
                TreeView::BTN_MOVE_DOWN => false,
                TreeView::BTN_MOVE_LEFT => false,
                TreeView::BTN_MOVE_RIGHT => false,
            ],                 
        'showIDAttribute' => false,
        'showTooltips' => false,
        'showNameAttribute' => false,
        'softDelete' => false,
        'cacheSettings' => ['enableCache' => true],
        //show => none removes the iconType etc setting under details                       
        'iconEditSettings'=>['show'=>'none'],
        //
        'showFormButtons'=>false,
        'breadcrumbs'=>[//'depth'=>null,
                        'glue'=>'&raquo;',
                        'activeCss'=>'kv-crumb-active',
                        'untitled'=>'Untitled'
                       ],
        //removing header below removes the search button and header                       
        //'wrapperTemplate'=>'{header}{tree}{footer}',         
        'wrapperTemplate'=>'{tree}',
        //removing the detail below removes the second column of view(s) 1 - 5
        'mainTemplate'=>'<div class="row">
                            <div class="col-sm-3">
                                {wrapper}
                            </div>
                            <div class="col-sm-9">
                                {detail}
                            </div>
                         </div>'                       
    ]); 
?>

The id of the actual node, or if I understand you correctly, the autoincrement id of the extended TreeView model can be retrieved simply by:

echo "Node id: ". $node->id;

at the bottom of your created view file. This is the id in:

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;

But this id does not really have any significance since if you refresh the database ie. delete previous records the autoincrement will start from the latest value.

If you are referring to the id of each of the 3 separate tables that make up the three different levels then this is where you will have to insert these different id field's into the tree model ie. after childallowed field so that you can populate these fields with the actual id from one of the different tables. This is done in your controller as shown in the previous example above. When you click on a node, only one of the 3 additional id fields will be populated ie. the other two will be null eg.

You can then access the information that you need for each node by using this id in a url to the table that holds the information. eg.

<?php
   use Yii;
   use yii\helpers\Url;
   use yii\helpers\Html;
?>
<div class="krajeeproducttree-product">
    <br>
        <?php
          if ($node->product_id > 0){
            echo Html::a('<h4>View House Details: ' .$node->name. '</h4>',Url::toRoute(['/product/view','id'=>$node->product_id]));
          }         
          if ($node->productsubcategory_id > 0){
            echo Html::a('<h4>View Street Details: ' .$node->name. '</h4>',Url::toRoute(['/productsubcategory/view','id'=>$node->productsubcategory_id]));
          }         
          if ($node->productcategory_id > 0){
            echo Html::a('<h4>View Postcode Details: ' .$node->name. '</h4>',Url::toRoute(['/productcategory/view','id'=>$node->productcategory_id]));
          }
          echo "Node id: ". $node->id;           
        ?>
    <br>
</div>

Krajee mentions this under Tree Model -> Model Attributes

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.



来源:https://stackoverflow.com/questions/62529619/how-to-pass-node-id-for-each-node-clicked-in-kartik-treeview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!