0

I followed up the documentaion and I don't know what is wrong. I just need to be able to use Tree widget for creating new node.

This is the model:

<?php

namespace common\models;

use Yii;
use creocoder\nestedsets\NestedSetsBehavior;

/**
 * This is the model class for table "categories".
 *
 * @property integer $id
 * @property integer $root
 * @property integer $lft
 * @property integer $rgt
 * @property integer $lvl
 * @property string $name
 * @property string $description
 * @property string $icon
 * @property integer $icon_type
 * @property integer $active
 * @property integer $selected
 * @property integer $disabled
 * @property integer $readonly
 * @property integer $visible
 * @property integer $collapsed
 * @property integer $movable_u
 * @property integer $movable_d
 * @property integer $movable_l
 * @property integer $movable_r
 * @property integer $removable
 * @property integer $removable_all
 *
 * @property CategoryItems[] $categoryItems
 */
class Categories extends \yii\db\ActiveRecord
{
  use \kartik\tree\models\TreeTrait {
        isDisabled as parentIsDisabled; // note the alias
    }

    public static $treeQueryClass; // change if you need to set your own TreeQuery
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'categories';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['root', 'lft', 'rgt', 'lvl', 'icon_type', 'active', 'selected', 'disabled', 'readonly', 'visible', 'collapsed', 'movable_u', 'movable_d', 'movable_l', 'movable_r', 'removable', 'removable_all'], 'integer'],
            [['lft', 'rgt', 'lvl', 'name'], 'required'],
            [['description'], 'string'],
            [['name'], 'string', 'max' => 60],
            [['icon'], 'string', 'max' => 255]
        ];


    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'root' => Yii::t('app', 'Root'),
            'lft' => Yii::t('app', 'Lft'),
            'rgt' => Yii::t('app', 'Rgt'),
            'lvl' => Yii::t('app', 'Lvl'),
            'name' => Yii::t('app', 'Name'),
            'description' => Yii::t('app', 'Description'),
            'icon' => Yii::t('app', 'Icon'),
            'icon_type' => Yii::t('app', 'Icon Type'),
            'active' => Yii::t('app', 'Active'),
            'selected' => Yii::t('app', 'Selected'),
            'disabled' => Yii::t('app', 'Disabled'),
            'readonly' => Yii::t('app', 'Readonly'),
            'visible' => Yii::t('app', 'Visible'),
            'collapsed' => Yii::t('app', 'Collapsed'),
            'movable_u' => Yii::t('app', 'Movable U'),
            'movable_d' => Yii::t('app', 'Movable D'),
            'movable_l' => Yii::t('app', 'Movable L'),
            'movable_r' => Yii::t('app', 'Movable R'),
            'removable' => Yii::t('app', 'Removable'),
            'removable_all' => Yii::t('app', 'Removable All'),
        ];
    }

    public function behaviors() {
        return [
            'tree' => [
                'class' => NestedSetsBehavior::className(),
                // 'treeAttribute' => 'tree',
                // 'leftAttribute' => 'lft',
                // 'rightAttribute' => 'rgt',
                 'depthAttribute' => 'lvl',
            ],
        ];
    }
    public function transactions()
    {
        return [
            self::SCENARIO_DEFAULT => self::OP_ALL,
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCategoryItems()
    {
        return $this->hasMany(CategoryItems::className(), ['category_id' => 'id']);
    }

    /**
     * @inheritdoc
     * @return CategoriesQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new CategoriesQuery(get_called_class());
    }
     public function isDisabled()
    {
        if (Yii::$app->user->id !== 'admin') {
            return true;
        }
        return $this->parentIsDisabled();
    }
}

And this is the view -index.php-

<?php

use yii\helpers\Html;
use yii\grid\GridView;
use common\models\Categories;
use kartik\tree\TreeView;

/* @var $this yii\web\View */
/* @var $searchModel common\models\CategoriesSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Categories');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="categories-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a(Yii::t('app', 'Create Categories'), ['create'], ['class' => 'btn btn-success']) ?>
    </p>

    <?php /*= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'root',
            'lft',
            'rgt',
            'lvl',
            // 'name',
            // 'description:ntext',
            // 'icon',
            // 'icon_type',
            // 'active',
            // 'selected',
            // 'disabled',
            // 'readonly',
            // 'visible',
            // 'collapsed',
            // 'movable_u',
            // 'movable_d',
            // 'movable_l',
            // 'movable_r',
            // 'removable',
            // 'removable_all',

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

</div>

The above gives the following screen shot: enter image description here

I tried to use creocoder yii2-nested-sets directly from the index action of CategoriesController but also it does not create any thing:

$countries = new Categories(['name' => 'bg']);
 $countries->makeRoot();

Edit

More detailed inspection about the issue, I found that the browser console generates the following error when trying to add new root:

POST http://localhost/inventory/backend/web/index.php?r=treemanager%2Fnode%2Fmanage&kvtree=-385354956 500 (Internal Server Error)

In addition, the targeted URL generates the following output:

{"name":"Exception","message":"This operation is not allowed.","code":0,"type":"yii\\base\\InvalidCallException","file":"C:\\xampp-2\\htdocs\\inventory\\vendor\\kartik-v\\yii2-tree-manager\\controllers\\NodeController.php","line":66,"stack-trace":["#0 C:\\xampp-2\\htdocs\\inventory\\vendor\\kartik-v\\yii2-tree-manager\\controllers\\NodeController.php(143): kartik\\tree\\controllers\\NodeController::checkValidRequest()","#1 [internal function]: kartik\\tree\\controllers\\NodeController->actionManage()","#2 C:\\xampp-2\\htdocs\\inventory\\vendor\\yiisoft\\yii2\\base\\InlineAction.php(55): call_user_func_array(Array, Array)","#3 C:\\xampp-2\\htdocs\\inventory\\vendor\\yiisoft\\yii2\\base\\Controller.php(151): yii\\base\\InlineAction->runWithParams(Array)","#4 C:\\xampp-2\\htdocs\\inventory\\vendor\\yiisoft\\yii2\\base\\Module.php(455): yii\\base\\Controller->runAction('manage', Array)","#5 C:\\xampp-2\\htdocs\\inventory\\vendor\\yiisoft\\yii2\\web\\Application.php(84): yii\\base\\Module->runAction('treemanager/nod...', Array)","#6 C:\\xampp-2\\htdocs\\inventory\\vendor\\yiisoft\\yii2\\base\\Application.php(375): yii\\web\\Application->handleRequest(Object(yii\\web\\Request))","#7 C:\\xampp-2\\htdocs\\inventory\\backend\\web\\index.php(18): yii\\base\\Application->run()","#8 {main}"]}
SaidbakR
  • 13,303
  • 20
  • 101
  • 195
  • 1
    I didn't use Kartik's version, only checked demos and docs, but as an alternative I can suggest using [my extension](https://github.com/arogachev/yii2-tree) for Nested Sets management. Maybe you will find it useful. – arogachev Aug 03 '15 at 04:14
  • @arogachev what is `frontend\modules\department\models\Department;`? Does it need a module? – SaidbakR Aug 03 '15 at 11:42
  • In addition using `composer require --prefer-dist arogachev/yii2-tree` leads to an error about not found pacakge: `Check the package spelling or your minimum-stability` – SaidbakR Aug 03 '15 at 12:30
  • 1
    We can discuss extension setup and usage problems in private chat. Contacts are listed in profile. – arogachev Aug 04 '15 at 08:22
  • Anything new on this? I also installed like in the docs. i can create root nodes, but they are always grey (disabled). I cannot do anything with them – kasoft Aug 31 '15 at 15:35

3 Answers3

3

I've encountered this before. You should insert a Root record in the tbl_category table manually,

eg:id=1,root=1,lft=1,rgt=1,lvl=0,name =Root

then you can add the node in the UI.

I thought this as the init data for the nested sets table begin to work.

Sampada
  • 2,931
  • 7
  • 27
  • 39
allenaware
  • 46
  • 2
  • I have posted a new [question](https://stackoverflow.com/questions/62529619/how-to-pass-node-id-for-each-node-clicked-in-kartik-treeview) related to treeview can you please see it? – Moeez Jun 24 '20 at 07:10
2

comment out the method isDisabled()

 public function isDisabled()
    {
        if (Yii::$app->user->id !== 'admin') {
            return true;
        }
        return $this->parentIsDisabled();
    }

http://demos.krajee.com/tree-manager#comment-2288987974

  • 2
    this is wrong you dont comment out the method instead you should use `isAdmin` option that can be set to tru or false while initializing the tree – Muhammad Omer Aslam Jul 13 '18 at 12:47
0

Add:

<?= Html::csrfMetaTags() ?>

To header of main layouts (default main.php). It working for me.

Anh Tuấn
  • 5
  • 1
  • 3
  • I have posted a new [question](https://stackoverflow.com/questions/62529619/how-to-pass-node-id-for-each-node-clicked-in-kartik-treeview) related to treeview can you please see it? – Moeez Jun 24 '20 at 07:10