Giter Site home page Giter Site logo

yii2-treegrid's Introduction

jQuery TreeGrid Extension for Yii 2

This is the jQuery TreeGrid extension for Yii 2. It encapsulates TreeGrid component in terms of Yii widgets, and thus makes using TreeGrid component in Yii applications extremely easy

Yii2 Latest Stable Version Total Downloads

Installation

The preferred way to install this extension is through composer.

Either run

php composer.phar require --prefer-dist leandrogehlen/yii2-treegrid "*"

or add

"leandrogehlen/yii2-treegrid": "*"

to the require section of your composer.json file.

Usage

Model

use yii\db\ActiveRecord;

/**
 * @property string $description
 * @property integer $parent_id
 */
class Tree extends ActiveRecord 
{

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tree';
    }  
    
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['description'], 'required'],
            [['description'], 'string'],
            [['parent_id'], 'integer']
        ];
    }
}

Controller

use yii\web\Controller;
use Yii;
use yii\data\ActiveDataProvider;

class TreeController extends Controller
{

    /**
     * Lists all Tree models.
     * @return mixed
     */
    public function actionIndex()
    {
        $query = Tree::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => false
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider
        ]);
    }

View

use leandrogehlen\treegrid\TreeGrid;
  
<?= TreeGrid::widget([
    'dataProvider' => $dataProvider,
    'keyColumnName' => 'id',
    'parentColumnName' => 'parent_id',
    'parentRootValue' => '0', //first parentId value
    'pluginOptions' => [
        'initialState' => 'collapsed',
    ],
    'columns' => [
        'name',
        'id',
        'parent_id',
        ['class' => 'yii\grid\ActionColumn']
    ]     
]); ?>

Adding resources

When is necessary to add other resource files, then should be used the Dependency Injection concept.

To use the saveState option it's necessary to add jquery.cookie.js.

//config/web.php
  
$config = [
  'id' => 'my-app',
  'components' => [
    ...
  ]
  ...
]

Yii::$container->set('leandrogehlen\treegrid\TreeGridAsset',[
    'js' => [
        'js/jquery.cookie.js',
        'js/jquery.treegrid.min.js',
    ]
]);

return $config;

yii2-treegrid's People

Contributors

dependabot[bot] avatar lav45 avatar leandrogehlen avatar pgyf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-treegrid's Issues

Search in view

Hi! Tell me please, How I can add filterModel and columns filter? Example, in GridView 'filterModel' => $searchModel,for column:[
'attribute'=>'articles_id',
'format' => 'html',
'value' => function($data){
if (!empty ($data->article))
return $data->article->title;
},
'filter' => \common\models\ArticlesComments::getArticlesList()
],`

Get result from another column

Hello,
I just want to get the result from another column and put it into next column for calculation and to save execution time.

example:

echo TreeGrid::widget([
	'dataProvider' => $dataProvider,
	'keyColumnName' => 'id',
	'parentColumnName' => 'PARENT_ID',
	'parentRootValue' => '', //first parentId value
	'pluginOptions' => [
		'initialState' => 'expanded', //collapsed
	],
	'columns' => [
		[
			'attribute' => 'JAN',
			'value' => function($model, $key, $index, $grid){
				$model['MONTH'] = 1;
				$resultJan = $model->bALANCE;
				return $resultJan;
			},
		],
		[
			'attribute' => 'FEB',
			'value' => function($model, $key, $index, $grid) use ($resultJan){
				$model['MONTH'] = 2;
				return $resultJan+$model->bALANCE;
			},
		],
	]     
]);

So, Here I want to use $resultJan into FEB column.

Grouping

I'm having an issue with the grouping.

One level deep nest / groups properly

If it's deeper than one level it isn't nesting the child elements under the proper parent attribute. However, the open and close toggle icon, opens and closes the correct elements event though they aren't in the right location on the grid. I don't know if it's because the PK and Parent fields are strings and not integers.
treegrid

Here is my exact config

TreeGrid::widget([
        'dataProvider' => $dataProvider,
        'keyColumnName' => 'id',
        'parentColumnName' => 'p_id',
        'pluginOptions' => [
            'initialState' => 'collapsed',
            'saveState' => true,
            'saveStateName' => 'locations-list-state'
        ],
        'columns' => [
            'name',
            'id',
            'p_id'
        ],
    ]);

multi levels won't work

I am trying to use the extension with multi-levels categories but it is only show two levels

Wrong ID on ActionColumn

Hi,
I setup such as for my TreeGrid:


<?= TreeGrid::widget([
        'dataProvider' => $dataProvider,
        //'filterModel' => $searchModel,
        'keyColumnName' => 'id',
        'parentColumnName' => 'parent_id',
        'parentRootValue' => '0', //first parentId value
        'pluginOptions' => [
            'initialState' => 'expanded',
        ],
        'columns' => [
            //['class' => 'yii\grid\SerialColumn'],
            'title',
            'alias',
            [
                'attribute' => 'language',
                'label' => Yii::t('backend', 'Language'),
                //'filter' => \backend\models\enums\BackendEnum::getLang(),
                'value' => function($model){
                    return \backend\models\enums\BackendEnum::getLangByCode($model->language);
                }
            ],
            [
                'attribute' => 'actived',
                'label' => Yii::t('backend', 'Status'),
                //'filter' => \backend\models\enums\BackendEnum::labelStatus(),
                'value' => function($model) {
                    return $model->actived ? Yii::t('backend', 'Publish') : Yii::t('backend', 'Unpublish');
                }
            ],
            [
                'class' => 'yii\grid\ActionColumn',
                'template' => '{update}{delete}',
            ],
        ],
    ]); ?>

But I found that, the ID on {update} and {delete} url was wrong, such as: the row model ID is 10, but the url for updating is "update?id=9".
I temporary fix that issue by add urlCreator to ActionColumn:
'urlCreator' => function ($action, $model, $key, $index) { if ($action === 'update') { $url = yii\helpers\Url::to(['update', 'id' => $model->id]); return $url; } if ($action === 'delete') { $url = yii\helpers\Url::to(['delete', 'id' => $model->id]); return $url; } }

Grouping Issue still not solved

@leandrogehlen following is my table structure.
CREATE TABLE IF NOT EXISTS category (
id int(255) NOT NULL AUTO_INCREMENT,
title varchar(255) DEFAULT NULL,
image varchar(100) DEFAULT NULL,
description varchar(55) DEFAULT NULL,
parent_id int(11) NOT NULL,
status int(11) NOT NULL,
PRIMARY KEY (id),
KEY fk_parent_id (parent_id)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=150 ;

can you please let me know whats wrong in it because I've updated my your extension in local four days ago. When I use your comparison "===" it gives me "no result" than I removed one = sign from it and got results but grouping is not well. As parent id 1 has many childs and extension results showed nothing
database

comparison

Please help me on this !!!

The recursivity of normalizeData method in TreeGrid class is potentially endless with only-numbers string as key and parentKey

The problem:

If the values of keyColumnName and parentColumnName fields are strings with only numeric character, the recursivity of normalizeData method in TreeGrid class is potentially endless.

Example case:

For example, if we have the follow data (informal code):

Node1: [key = "1", parentKey = null]

Node2: [key = "01", parentKey = "1"]

Node3: [key = "001", parentKey = "01"]

When is searching then Node2's children (value of $parentId parameter is "01"), because Node2's parentKey is "1", the condition ArrayHelper::getValue($element, $this->parentColumnName) == $parentId is evaluated true, therefore a new call to normalizeData is thrown to search (again) the Node2's children.

Suggested modification:

Use the type-strict comparation operator (===) instead the double equal operator (==).

ArrayHelper::getValue($element, $this->parentColumnName) === $parentId

I Cant install

  • leandrogehlen/yii2-treegrid 1.0.1 requires bower-asset/jquery-treegrid 0.3.0 -> no matching package found.

Help me

Pagination is not provided

When generating a tree, in which more than 20 elements necessary pagination. It is not provided?
in yii\data\Pagination property defaultPageSize = 20

Installation problem

Can't install with php composer.phar require --prefer-dist leandrogehlen/yii2-treegrid "*", get the following output:

>php composer.phar require --prefer-dist leandrogehlen/yii2-treegrid "*"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Installation request for leandrogehlen/yii2-treegrid * -> satisfiable by leandrogehlen/yii2-treegrid[dev-master].
    - leandrogehlen/yii2-treegrid dev-master requires bower-asset/jquery-treegrid 0.3.0 -> no matching package found.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Installation failed, reverting ./composer.json to its original content.

May be it is related with dependency bower-asset/jquery-treegrid: 0.3.0?

Bug for actiongrid buttons

HI, your treegrid has a bug.

Not correct url provided for ActionColumn(grid) buttons like view, edit, delete, etc..

Reason:
You get key from dataProvided when list is not sorted and put them for sorted list.

How to fix:
TreeGrid.php:

  1. need to change $key = $keys[$index]; on $key = $model['id'];
  2. remove $keys = $this->dataProvider->getKeys();(as not needed);

Partial loading of subtrees

Hi,

any plans to implement a partial load of a subtree? If you have a really big dataset, the functioallity might break?

Best Philipp

Loose comparison in normalizeData()

When comparing parent IDs the function normalizeData() uses loose comparison:

if ($element[$this->parentColumnName] == $parentId) { [...] }

This can result in false positives (which ultimately can lead to recursive hierarchies, i.e. infinite loops during code execution).
Example:

$element[$this->parentColumnName] = 0;   // int(0)
$parentId = 'p1';   // string(2) "p1"
$element[$this->parentColumnName] == $parentId   // true

Using strict comparison will prevent this behaviour:

if ($element[$this->parentColumnName] === $parentId) { [...] }

Example:

$element[$this->parentColumnName] = 0;   // int(0)
$parentId = 'p1';   // string(2) "p1"
$element[$this->parentColumnName] === $parentId   // false

It cost me about four days to figure this out. D'oh! ๐Ÿ˜ฃ

Tree formatting is lost when parentRootValue is not 0

Hi, I am implementing "zoom-in" and zoom-out actions with TreeGrid widget, and have a problem with properly rendering TreeGrid when I zoom in to the level when parentRootValue is not 0.

The zoom-in action is defined in controller as follows:

public function actionZoomin($id)
    {
      $branch_ids = Tgstep::getBranch($id); // getBranch returns the ids of this element and all children
      $query = Tgstep::find(['is_deleted'=>false])->where(['id'=>$branch_ids]);
      $model = $this->findModel($id);
      $dataProvider = new ActiveDataProvider([
          'query' => $query,
          'pagination' => false,
          'sort' => [
            'defaultOrder' => [
              'parent_id' => SORT_ASC,
              'position' => SORT_ASC,
            ]
          ],
      ]);

        return $this->render('zoom', [
            'dataProvider' => $dataProvider,
            'root_id' => $model->parent_id,
        ]);
    }

The corresponding view is as follows:

echo TreeGrid::widget([
    'dataProvider' => $dataProvider,
    'keyColumnName' => 'id',
    'parentColumnName' => 'parent_id',
    'parentRootValue' => $root_id,
    'pluginOptions' => [
      // zoom-in doesn't work if 'initialState' is not 'expanded'!
        'initialState' => 'expanded',
        'expanderExpandedClass' => 'glyphicon glyphicon-chevron-down',
        'expanderCollapsedClass' => 'glyphicon glyphicon-chevron-right',
    ],
    'columns' => [
      'step_name',
     'parent_id',
     'id',
     [
        'class' => 'yii\grid\ActionColumn',
        'template' => '{zoomin}',
        'buttons' => [
          'zoomin' => function ($url) {
            return Html::a('<span class="glyphicon glyphicon-zoom-in"></span>',
              $url, [
                'title' => 'zoomin',
                'data-pjax' => '0',
              ]);
          }],
        'urlCreator' => function ($action, $model, $key, $index) {
          if ($action === 'zoomin') {
            $url = Url::toRoute(['tgstep/zoomin', 'id' => $model->id]);
            return $url;
          }
         }
      ]
   ]
]);
?>

The zoom-in works as I expect it. That is, when I click zoom-in in the action column, the TreeGrid is reduced to the element and all its children. But the hierarchy and indentation are shown in TreeGrid only for the top level elements (i.e. only those elements with parent_id = 0).

Is there a way to fix this? Thanks very much in advance for help.

Problem if use parentRootValue

I need to show tree of subcategories.
In dataProvider I have all cats tree
I use params:

'dataProvider' => $dataProvider,
'keyColumnName' => 'id',
'parentColumnName' => 'parent_id',
'parentRootValue' => 2,

parentRootValue= 2 - ID of parent category I need to...
All subcats are showing in right order but expande/collapse and tree-view not working in this case...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.