PHP code example of demi / sort

1. Go to this page and download the library: Download demi/sort library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

demi / sort example snippets


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

<?= GridView::widget([
    // ...
    'columns' => [
        // ...
        [
            'class' => 'demi\sort\SortColumn',
            'action' => 'change-sort', // optional
        ],
    ],
]); 

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'sort' => ['defaultOrder' => ['sort' => SORT_ASC]],
]);

$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]);
}

// sort model down
$model->changeSorting(SORT_DESC);

// sort model up
$model->changeSorting(SORT_DESC);

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