demi / sort
Yii2 behavior for sorting models
Installs: 2 073
Dependents: 0
Suggesters: 0
Security: 0
Stars: 2
Watchers: 6
Forks: 6
Open Issues: 0
Type:yii2-extension
Requires
- php: >=5.4.0
- yiisoft/yii2: *
This package is auto-updated.
Last update: 2024-10-27 22:35:39 UTC
README
Yii2 behavior to sort models
Installation
Run
composer require "demi/sort" "~1.0"
Configuration
In model file add sort behavior:
public function behaviors() { return [ // ... 'sortBehavior' => [ 'class' => 'demi\sort\SortBehavior', 'sortConfig' => [ 'sortAttribute' => 'sort', 'condition' => function ($query, $model) { /* @var $query \yii\db\Query */ /* @var $model self */ $query->andWhere(['category_id' => $model->category_id]); }, ], ], ]; }
Usage
In GridView:
<?= GridView::widget([ // ... 'columns' => [ // ... [ 'class' => 'demi\sort\SortColumn', 'action' => 'change-sort', // optional ], ], ]); ?>
Don't forget set default order! usually CategorySearch::search()
$dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort' => ['defaultOrder' => ['sort' => SORT_ASC]], ]);
In view file:
$canSortDown = $model->canSort(SORT_DESC); $canSortUp = $model->canSort(SORT_ASC); if ($canSortDown) { echo Html::a('Down', ['change-sort', 'id' => $model->id, 'direction' => SORT_DESC]); } if ($canSortUp) { echo Html::a('Up', ['change-sort', 'id' => $model->id, 'direction' => SORT_ASC]); }
In conrtoller/model file:
// sort model down $model->changeSorting(SORT_DESC); // sort model up $model->changeSorting(SORT_DESC);
Bonus: Sort Action
Add this code to you controller:
public function actions() { return [ 'change-sort' => [ 'class' => 'demi\sort\SortAction', 'modelClass' => \common\models\Category::className(), // optionaly 'afterChange' => function ($model) { if (!Yii::$app->request->isAjax) { return Yii::$app->response->redirect(Url::to(['update', 'id' => $model->category_id])); } else { return Yii::$app->controller->renderPartial('index', ['model' => $model]); } }, // or 'redirectUrl' => ['index'], // or 'redirectUrl' => function ($model) { return ['update', 'id' => $model->id]; }, 'canSort' => Yii::$app->user->can('admin'), // or 'canSort' => function ($model) { return Yii::$app->user->id == $model->user_id; }, ], ]; }