phpframeworksyiinested-setsnested-set-model

Yii Extension - nestedsetbehavior not saving


I'm trying to save a node with the extension "NestedSetBehvaior": http://www.yiiframework.com/extension/nestedsetbehavior/

But it is not saving anything in the database..

I tried using the schema that comes with the extension (extensions/yiiext/behaviors/trees/schema.sql)..

I also added the "title" column which was not included.

I then generated the Controller, Model & CRUD with Gii and added this to the newly created Model: Category.php

    public function behaviors()
    {
        return array(
            'nestedSetBehavior'=>array(
                'class'=>'ext.yiiext.behaviors.model.trees.NestedSetBehavior',
                'leftAttribute'=>'lft',
                'rightAttribute'=>'rgt',
                'levelAttribute'=>'level',
            ),
        );
    }

I Also placed the NestedSetBehavior.php in protected/extensions/yiiext/behaviors/model/trees/

And then I added this to the controller indexAction:

$root=new Category;
$root->title='Mobile Phones';
$root->saveNode();

What could possibly be wrong?

And also, which method would you recommend for storing multiple trees for multiple users (3000+)? Imagine a tree with unlimited depth..


Solution

  • I've managed to find the solution on my own. The problem was in the model 'Category'. I changed the validation rules so that 'lft', 'rgt' and 'level' are not required, since these are automatically added by NestedSetBehavior.

    Before change:

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('lft, rgt, level', 'required'),
            array('level', 'numerical', 'integerOnly'=>true),
            array('root, lft, rgt', 'length', 'max'=>10),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, root, lft, rgt, level', 'safe', 'on'=>'search'),
        );
    }
    

    After Change:

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            //array('lft, rgt, level', 'required'),
            array('level', 'numerical', 'integerOnly'=>true),
            array('root, lft, rgt', 'length', 'max'=>10),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, root, lft, rgt, level', 'safe', 'on'=>'search'),
        );
    }
    

    It's working perfectly now.