Sorting behavior for Active Record models
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
LICENSE
README.md
SortAction.php
SortBehavior.php
SortColumn.php
composer.json

README.md

yii2-sort

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;
                },
        ],
    ];
}