demi/sort Yii2 behavior for sorting models

behaviorsortingsort

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

Statistics

Downloads
GitHub Stars
GitHub Forks

Releases

Comments



1.0.1 is the latest of 2 releases



GPL-3.0-or-later license
Stats
2 github stars & 6 github forks
0 downloads in the last day
17 downloads in the last 30 days
2077 total downloads