-
Notifications
You must be signed in to change notification settings - Fork 1
/
ToggleColumn.php
90 lines (79 loc) · 1.98 KB
/
ToggleColumn.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
<?php
namespace yii2mod\toggle;
use Yii;
use yii\grid\DataColumn;
use yii\helpers\Html;
use yii\web\View;
/**
* Class ToggleColumn
*
* @package yii2mod\toggle
*/
class ToggleColumn extends DataColumn
{
/**
* Toggle action that will be used as the toggle action in your controller
*
* @var string
*/
public $action = 'toggle';
/**
* Whether to use ajax or not
*
* @var bool
*/
public $enableAjax = true;
/**
* @inheritdoc
*/
public function init()
{
parent::init();
if ($this->enableAjax) {
$this->registerJs();
}
}
/**
* @inheritdoc
*/
protected function renderDataCellContent($model, $key, $index)
{
$attribute = $this->attribute;
$value = $model->$attribute;
$url = [$this->action, 'id' => $model->id, 'attribute' => $attribute];
if ($value === null || $value == true) {
$icon = 'ok';
$title = Yii::t('app', 'Off');
} else {
$icon = 'remove';
$title = Yii::t('app', 'On');
}
return Html::a(
'<span class="glyphicon glyphicon-' . $icon . '"></span>',
$url,
[
'title' => $title,
'class' => 'toggle-column',
'data-method' => 'post',
'data-pjax' => '0',
]
);
}
/**
* Registers the ajax JS
*/
public function registerJs()
{
$js = <<< JS
$("a.toggle-column").on("click", function(e) {
e.preventDefault();
$.post($(this).attr("href"), function(data) {
var pjaxId = $(e.target).closest(".grid-view").parent().attr("id");
$.pjax.reload({container:"#" + pjaxId, timeout: 5000});
});
return false;
});
JS;
$this->grid->view->registerJs($js, View::POS_READY, 'yii2mod-toggle-column');
}
}