PHP code example of paulzi / yii2-sortable

1. Go to this page and download the library: Download paulzi/yii2-sortable 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/ */

    

paulzi / yii2-sortable example snippets


$this->createIndex('parent_sort', '{{%item}}', ['parent_id', 'sort']);

use paulzi\sortable\SortableBehavior;

class Sample extends \yii\db\ActiveRecord
{
    public function behaviors() {
        return [
            [
                'class' => SortableBehavior::className(),
            ],
        ];
    }
}

public function behaviors()
{
    return [
        [
            'class' => SortableBehavior::className(),
            'query' => ['parent_id'],
        ]
    ];
}

public function behaviors()
{
    return [
        [
            'class' => SortableBehavior::className(),
            'query' => function ($model) {
                $tableName = $model->tableName();
                return $model->find()->andWhere(["{$tableName}.[[parent_id]]" => $model->parent_id]);
            },
        ]
    ];
}

$model = Sample::findOne(1);
$position = $model->getSortablePosition();

$model = new Sample(['parent_id' => 1]);
$model->moveFirst()->save(); // inserting new node

$model = Sample::findOne(1);
$model->moveLast()->save(); // move existing node

$model = Sample::findOne(1);
$model->moveTo(-33, true)->save(); // move to position -33, and move existing items forward
$model = Sample::findOne(2);
$model->moveTo(4, false)->save(); // move to position 4, and move existing items backward

$model1 = new Sample(['parent_id' => 1]);
$model2 = Sample::findOne(2);
$model1->moveBefore($model2)->save(); // move $model1 before $model2

$model1 = Sample::findOne(1);
$model2 = Sample::findOne(2);
$model1->parent_id = $model2->parent_id;
$model1->moveAfter($model2)->save(); // move $model1 after $model2 with change scope

$model = Sample::findOne(1);
$model->reorder(true); // reorder with center zero
$model = Sample::findOne(2);
$model->reorder(false); // reorder from zero