You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

144 lines
3.5 KiB

<?php
/**
* Created by Error202
* Date: 04.06.2018
*/
namespace backend\components;
use yii\grid\DataColumn;
use yii\helpers\Html;
use yii\web\View;
use Yii;
class ToggleColumn extends DataColumn
{
/**
* Toggle action that will be used as the toggle action in your controller
* @var string
*/
public string $action = 'toggle';
/**
* @var string pk field name
*/
public string $primaryKey = 'primaryKey';
/**
* Whether to use ajax or not
* @var bool
*/
public bool $enableAjax = true;
/**
* @var string glyphicon for 'on' value
*/
public string $iconOn = 'ok';
/**
* @var string glyphicon for 'off' value
*/
public string $iconOff = 'remove';
/**
* @var string|null text to display on the 'on' link
*/
public ?string $onText = null;
/**
* @var string|null text to display on the 'off' link
*/
public ?string $offText = null;
/**
* @var string|bool text to display next to the 'on' link
*/
public string|bool $displayValueText = false;
/**
* @var string|null text to display next to the 'on' link
*/
public ?string $onValueText = null;
/**
* @var string|null text to display next to the 'off' link
*/
public ?string $offValueText = null;
public function init()
{
if ($this->onText === null) {
$this->onText = Yii::t('main', 'On');
}
if ($this->offText === null) {
$this->offText = Yii::t('main', 'Off');
}
if ($this->onValueText === null) {
$this->onValueText = Yii::t('main', 'Active');
}
if ($this->offValueText === null) {
$this->offValueText = Yii::t('main', 'Inactive');
}
if ($this->enableAjax) {
$this->registerJs();
}
}
/**
* Registers the ajax JS
*/
public function registerJs()
{
if (Yii::$app->request->isAjax) {
return;
}
$js = <<<'JS'
$(document.body).on("click", "a.toggle-column", function(e) {
e.preventDefault();
$.post($(this).attr("href"), function(data) {
var pjaxId = $(e.target).closest("[data-pjax-container]").attr("id");
$.pjax.reload({container:"#" + pjaxId});
});
return false;
});
JS;
$this->grid->view->registerJs($js, View::POS_READY, 'zx-toggle-column');
}
/**
* @inheritdoc
*/
protected function renderDataCellContent($model, $key, $index)
{
$url = [$this->action, 'id' => $model->{$this->primaryKey}];
$attribute = $this->attribute;
$value = $model->$attribute;
if ($value === null || $value == true) {
$icon = $this->iconOn;
$title = $this->offText;
$valueText = $this->onValueText;
$color = 'green';
} else {
$icon = $this->iconOff;
$title = $this->onText;
$valueText = $this->offValueText;
$color = 'red';
}
return Html::a(
'<span class="glyphicon glyphicon-' . $icon . '"></span>',
$url,
[
'title' => $title,
'class' => 'toggle-column',
'style' => 'color:' . $color,
'data-method' => 'post',
'data-pjax' => '0',
]
) . ($this->displayValueText ? " {$valueText}" : '');
}
}