PHPackages                             arogachev/yii2-sortable - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Framework](/categories/framework)
4. /
5. arogachev/yii2-sortable

ActiveYii2-extension[Framework](/categories/framework)

arogachev/yii2-sortable
=======================

Sortable ActiveRecord for Yii 2 framework

0.1.6(10y ago)1637.0k↓40.9%9[17 issues](https://github.com/arogachev/yii2-sortable/issues)4BSD-3-ClausePHP

Since Apr 12Pushed 2y ago2 watchersCompare

[ Source](https://github.com/arogachev/yii2-sortable)[ Packagist](https://packagist.org/packages/arogachev/yii2-sortable)[ Docs](https://github.com/arogachev/yii2-sortable)[ RSS](/packages/arogachev-yii2-sortable/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (3)Versions (8)Used By (4)

Yii 2 Sortable
==============

[](#yii-2-sortable)

This extension allows to manage order of ActiveRecord models via different behaviors. Choose one to fit your needs.

[![Latest Stable Version](https://camo.githubusercontent.com/79ade065eb50efd9a937c8bac7048f555034b0c96cfc3e939e8e66c29200b71d/68747470733a2f2f706f7365722e707567782e6f72672f61726f6761636865762f796969322d736f727461626c652f762f737461626c65)](https://packagist.org/packages/arogachev/yii2-sortable)[![Total Downloads](https://camo.githubusercontent.com/0409a45237a5aa453d8d6d85699fe8f6aeee69323d101a0a5cb33342b79867c9/68747470733a2f2f706f7365722e707567782e6f72672f61726f6761636865762f796969322d736f727461626c652f646f776e6c6f616473)](https://packagist.org/packages/arogachev/yii2-sortable)[![Latest Unstable Version](https://camo.githubusercontent.com/3916a573ecc0d853c19f0960b84dd2eb409af4ee8a7aeb2d24e2b103866090c1/68747470733a2f2f706f7365722e707567782e6f72672f61726f6761636865762f796969322d736f727461626c652f762f756e737461626c65)](https://packagist.org/packages/arogachev/yii2-sortable)[![License](https://camo.githubusercontent.com/afd15a8dae90b977006928c3f3e75e79973f21cb8c9f1fdb7589f6cac9f27dbe/68747470733a2f2f706f7365722e707567782e6f72672f61726f6761636865762f796969322d736f727461626c652f6c6963656e7365)](https://packagist.org/packages/arogachev/yii2-sortable)

- [Installation](#installation)
- [Features](#features)
- [Behaviors types](#behaviors-types)
- [Preparing table structure](#preparing-table-structure)
- [Attaching behavior](#attaching-behavior)
- [Configuring behavior](#configuring-behavior)
- [Changing order of models inside sortable scope](#changing-order-of-models-inside-sortable-scope)
- [GUI for changing order](#gui-for-changing-order)
- [Custom GUI for changing order](#custom-gui-for-changing-order)

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist arogachev/yii2-sortable

```

or add

```
"arogachev/yii2-sortable": "*"

```

to the require section of your `composer.json` file.

Features
--------

[](#features)

- Several implemented algorithms. Choose one to fit your needs.
- Setting of sortable scope. In this case the order of models in each scope is managed separately.
- Additional setting of sortable condition. For example, if the model can be marked as active or deleted, you can additionally specify that condition and it will be considered when changing these attributes values.
- Order auto adjustment when adding new model, removing out of sortable scope, moving between the sortable scopes.
- Changing order of models inside sortable scope.
- GUI for managing order of models in `GridView` (`SortableColumn`).
- Sort controller for simplifying writing of own GUI

Behaviors types
---------------

[](#behaviors-types)

There are several behaviors to choose from:

- `ContinuousNumericalSortableBehavior`
- `IntervalNumericalSortableBehavior`
- `LinkedListSortableBehavior` (currently not implemented)

The first two are numerical behaviors and they have one thing in common - they store position of each model as number.

`ContinuousNumericalSortableBehavior`:

Stored number is equal to exact position.

**Advantages:**

- You can get current position without additional queries

**Disadvantages:**

- Amount of `UPDATE` queries can be large depending on amount of sortable models and situation. It relates to adjustment order. For example no extra queries will be performed in case of switching models with 3 and 4 position (only 2 `UPDATE` queries). But if you have 1000 models and you move the last model to the very beginning there will be 1000 `UPDATE` queries (so it depends on interval length).

`IntervalNumericalSortableBehavior`:

The numbers are stored with certain intervals (initially with equal size). You can see the basic description of the used algorithm [here](http://stackoverflow.com/questions/6804166/what-is-the-most-efficient-way-to-store-a-sort-order-on-a-group-of-records-in-a/6804302#6804302).

**Advantages:**

- For adding or deletion there is no need to adjust order of other models. And for changing order for most of the times only few `SELECT` and one `UPDATE` query will be executed. The full adjustment of order of all models inside of sortable scope is only required in case of conflict. The conflicts don't happen often if you set interval size big enough and don't move models to the same position over and over again.

**Disadvantages:**

- For getting positions of models extra query is used.

### Preparing table structure

[](#preparing-table-structure)

In case of using numerical behaviors add this to migration:

```
$this->addColumn('table_name', 'sort', Schema::TYPE_INTEGER . ' NOT NULL');
```

Attaching behavior
------------------

[](#attaching-behavior)

Add this to your model for minimal setup:

```
use arogachev\sortable\behaviors\numerical\ContinuousNumericalSortableBehavior;
```

```
/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        [
            'class' => ContinuousNumericalSortableBehavior::className(),
        ],
    ];
}
```

### Configuring behavior

[](#configuring-behavior)

**Common properties for all behaviors:**

`scope` - sortable scope. Specify it if you want to separate models by condition and manage order independently in each one. It expects closure returning `ActiveQuery`, but `where` part must be specified as array only. Example:

```
function () {
    return Question::find()->where(['test_id' => $this->test_id]);
}
```

You can use `$model` parameter to generate model related queries:

```
function ($model) {
    return $model->getNeighbors();
}
```

where `getNeighbors()` implementation can be like this:

```
/**
 * @return \yii\db\ActiveQuery
 */
public function getNeighbors()
{
    return static::find()->where(['parent_id' => $this->parent_id]);
}
```

If this property is not set, all models considered as one sortable scope.

`sortableCondition` - additional property to filter sortable models. You should specify it as conditional array:

```
[
    'is_active' => 1,
    'is_deleted' => 0,
],
```

`prependAdded` - insert added sortable model to the beginning of sortable scope. Defaults to `false` which means inserting to the end.

`access` - closure for checking access to sort for current user. Example:

```
function () {
    return Yii::$app->user->can('questions.sort');
}
```

**Numerical behaviors properties:**

`sortAttribute` - name of the sort attribute column. Defaults to `sort`.

**`IntervalNumericalSortableBehavior` properties:**

`intervalSize` - size of the interval. Defaults to `1000`. When specifying bigger numbers, conflicts will happen less often.

`increasingLimit` - the number of times user can continuously move item to the end of the sortable scope. Used to prevent increasing of numbers. Defaults to `10`.

Changing order of models inside sortable scope
----------------------------------------------

[](#changing-order-of-models-inside-sortable-scope)

The behavior provides few methods to change any sortable model order:

- `moveToPosition($position)` - basic method for moving model to any position inside sortable scope
- `moveBefore($pk = null)` - move model before another model of this sortable scope. If `$pk` is not specified it will be moved to the very end
- `moveAfter($pk = null)` - move model after another model of this sortable scope If `$pk` is not specified it will be moved to the very beginning
- `moveBack()` - move back by one position
- `moveForward()` - move forward by one position
- `moveAsFirst()` - move to the very beginning
- `moveAsLast()` - move to the very end

GUI for changing order
----------------------

[](#gui-for-changing-order)

There is special `SortableColumn` for `GridView`.

**Features:**

- It doesn't force you to use the whole another `GridView`
- No need to attach additional actions every time
- Multiple `GridView` on one page support
- Displaying current position
- Inline editing of current position
- Moving with drag and drop (with `jQuery UI Sortable`) with special handle icon, so you can interact with other data without triggering sort change
- Moving back and forward by one position
- Moving as first and last

Include once this to your application config:

```
'controllerMap' => [
    'sort' => [
        'class' => 'arogachev\sortable\controllers\SortController',
    ],
],
```

Then configure `GridView`:

- Wrap it with `Pjax` widget for working without page reload
- Add `id` for unchangeable root container
- Include column in `columns` section

```
use arogachev\sortable\grid\SortableColumn;
```

```

```

You can configure display through `template` and `buttons` properties (similar to [ActionColumn](http://www.yiiframework.com/doc-2.0/yii-grid-actioncolumn.html)).

The available tags are:

- `currentPosition`
- `moveWithDragAndDrop`
- `moveForward`
- `moveBack`
- `moveAsFirst`
- `moveAsLast`

You can extend it with your own. Example of overriding:

```
'template' => '{moveWithDragAndDrop}
{currentPosition}
{moveForward} {moveBack}',
'buttons' => [
    'moveForward' => function () {
        return Html::tag('i', '', [
            'class' => 'fa fa-arrow-circle-left',
            'title' => Yii::t('sortable', 'Move forward'),
        ]);
    },
    'moveBack' => function () {
        return Html::tag('i', '', [
            'class' => 'fa fa-arrow-circle-right',
            'title' => Yii::t('sortable', 'Move back'),
        ]);
    },
],
```

Custom GUI for changing order
-----------------------------

[](#custom-gui-for-changing-order)

If you want to write your own GUI for changing order without using `GridView`, you can use the `SortController` actions:

- `move-before` (requires `pk` of the next element after move sent via `POST`)
- `move-after` (requires `pk` of the previous element after move sent via `POST`)
- `move-back`
- `move-forward`
- `move-as-first`
- `move-as-last`
- `move-to-position` (requires `position` sent via `POST`)

For all of the actions these two parameters must exist in `POST`:

- `modelClass` - model full class name with namespace
- `modelPk` - moved model primary key value (pass object in case of primary keys)

###  Health Score

32

—

LowBetter than 72% of packages

Maintenance0

Infrequent updates — may be unmaintained

Popularity38

Limited adoption so far

Community20

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 90% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~48 days

Recently: every ~70 days

Total

7

Last Release

3765d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/1714d1321ae502a7f9bfd21e9a4cb7467306491280fa8b5d43d549434abd5177?d=identicon)[arogachev](/maintainers/arogachev)

---

Top Contributors

[![arogachev](https://avatars.githubusercontent.com/u/8326201?v=4)](https://github.com/arogachev "arogachev (18 commits)")[![giannisdag](https://avatars.githubusercontent.com/u/2151129?v=4)](https://github.com/giannisdag "giannisdag (1 commits)")[![Hector68](https://avatars.githubusercontent.com/u/920564?v=4)](https://github.com/Hector68 "Hector68 (1 commits)")

---

Tags

sortablesortyii2Behavioractive-recordgridview

### Embed Badge

![Health badge](/badges/arogachev-yii2-sortable/health.svg)

```
[![Health](https://phpackages.com/badges/arogachev-yii2-sortable/health.svg)](https://phpackages.com/packages/arogachev-yii2-sortable)
```

###  Alternatives

[yiisoft/yii2-redis

Redis Cache, Session and ActiveRecord for the Yii framework

48011.7M245](/packages/yiisoft-yii2-redis)[yiisoft/yii2-elasticsearch

Elasticsearch integration and ActiveRecord for the Yii framework

4371.9M15](/packages/yiisoft-yii2-elasticsearch)[yiisoft/yii2-mongodb

MongoDB extension for the Yii framework

3312.1M45](/packages/yiisoft-yii2-mongodb)[yiisoft/yii2-sphinx

Sphinx full text search engine extension for the Yii framework

180997.7k5](/packages/yiisoft-yii2-sphinx)[skeeks/cms

SkeekS CMS — control panel and tools based on php framework Yii2

13825.6k47](/packages/skeeks-cms)[himiklab/yii2-sortable-grid-view-widget

Sortable modification of standard Yii2 GridView widget

80351.1k7](/packages/himiklab-yii2-sortable-grid-view-widget)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
