forked from sjaakp/yii2-sortable-behavior
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortableGridView.php
100 lines (87 loc) · 2.84 KB
/
SortableGridView.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
/**
* MIT licence
* Version 1.0.1
* Sjaak Priester, Amsterdam 28-08-2014 ... 01-01-2019.
* https://sjaakpriester.nl
*
* Sortable GridView for Yii 2.0
*
* GridView which is made sortable by means of the jQuery Sortable widget.
* After each order operation, order data are posted to $orderUrl in the following format:
* - $_POST["key"] - the primary key of the sorted ActiveRecord,
* - $_POST["pos"] - the new position, zero-indexed.
*
*/
namespace sjaakp\sortable;
use yii\grid\GridView;
use yii\jui\JuiAsset;
use yii\helpers\Json;
use yii\helpers\Url;
use yii\web\JsExpression;
/**
* Class SortableGridView
* @package sjaakp\sortable
*/
class SortableGridView extends GridView {
/**
* @var array|string
* The url which is called after an order operation.
* The format is that of yii\helpers\Url::toRoute.
* The url will be called with the POST method and the following data:
* - key the primary key of the ordered ActiveRecord,
* - pos the new, zero-indexed position.
*
* Example: ['movie/order-actor', 'id' => 5]
*/
public $orderUrl;
/**
* @var array
* The options for the jQuery sortable object.
* See http://api.jqueryui.com/sortable/ .
* Notice that the options 'helper' and 'update' will be overwritten.
* Default: empty array.
*/
public $sortOptions = [];
/**
* @var boolean|string
* The 'axis'-option of the jQuery sortable. If false, it is not set.
*/
public $sortAxis = 'y';
public function init()
{
parent::init();
$classes = isset($this->options['class']) ? $this->options['class'] : '';
$classes .= ' sortable';
$this->options['class'] = trim($classes);
$view = $this->getView();
JuiAsset::register($view);
$id = $this->getId();
$url = Url::toRoute($this->orderUrl);
$sortOpts = array_merge($this->sortOptions, [
'helper' => new JsExpression('function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
}'),
'update' => new JsExpression("function(e, ui) {
jQuery('#{$id}').addClass('sorting');
jQuery.ajax({
type: 'POST',
url: '$url',
data: {
key: ui.item.data('key'),
pos: ui.item.index()
},
complete: function() {
jQuery('#{$id}').removeClass('sorting');
}
});
}")
]);
if ($this->sortAxis) $sortOpts['axis'] = $this->sortAxis;
$sortJson = Json::encode($sortOpts);
$view->registerJs("jQuery('#{$id} tbody').sortable($sortJson);");
}
}