Completed
Push — master ( 6aed65...9d47e6 )
by Antonio
02:08
created

ToggleColumn::renderDataCell()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 0
cts 10
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 7
nc 2
nop 3
crap 6
1
<?php
2
3
/*
4
 * This file is part of the 2amigos/yii2-grid-view-library project.
5
 * (c) 2amigOS! <http://2amigos.us/>
6
 * For the full copyright and license information, please view
7
 * the LICENSE file that was distributed with this source code.
8
 */
9
10
namespace dosamigos\grid\columns;
11
12
use dosamigos\grid\bundles\ToggleColumnAsset;
13
use Yii;
14
use yii\base\InvalidConfigException;
15
use yii\base\Model;
16
use yii\helpers\Html;
17
use yii\helpers\Url;
18
19
/**
20
 * ToggleColumn Allows to modify the value of column on the fly. This type of column is good when you wish to modify
21
 * the value of a displayed model that has two states: yes-no, true-false, 1-0, etc...
22
 */
23
class ToggleColumn extends DataColumn
24
{
25
    /**
26
     * @var int the value to check against `On` state.
27
     */
28
    public $onValue = 1;
29
    /**
30
     * @var string the label for the toggle button. Defaults to "Check".
31
     *             Note that the label will not be HTML-encoded when rendering.
32
     */
33
    public $onLabel;
34
    /**
35
     * @var string the label for the toggle button. Defaults to "Uncheck".
36
     *             Note that the label will not be HTML-encoded when rendering.
37
     */
38
    public $offLabel;
39
    /**
40
     * @var string the label for the NULL value toggle button. Defaults to "Not Set".
41
     *             Note that the label will not be HTML-encoded when rendering.
42
     */
43
    public $emptyLabel;
44
    /**
45
     * @var string the glyph icon toggle button "checked" state.
46
     *             You may set this property to be false to render a text link instead.
47
     */
48
    public $onIcon = 'glyphicon glyphicon-ok-circle';
49
    /**
50
     * @var string the glyph icon toggle button "unchecked" state.
51
     *             You may set this property to be false to render a text link instead.
52
     */
53
    public $offIcon = 'glyphicon glyphicon-remove-circle';
54
    /**
55
     * @var string the glyph icon toggle button "empty" state (example for null value)
56
     */
57
    public $emptyIcon = 'glyphicon glyphicon-question-sign';
58
    /**
59
     * @var boolean display button with text or only icon with label tooltip
60
     */
61
    public $asText = false;
62
    /**
63
     * @var string Name of the action to call and toggle values. Defaults to `toggle`.
64
     * @see [[ToggleAction]] for an easy way to use with your controller
65
     */
66
    public $url = ['toggle'];
67
    /**
68
     * @var string a javascript function that will be invoked after the toggle ajax call.
69
     *
70
     * The function signature is `function(success, data)`.
71
     *
72
     * - success:  status of the ajax call, true if the ajax call was successful, false if the ajax call failed.
73
     * - data: the data returned by the server in case of a successful call or XHR object in case of error.
74
     *
75
     * Note that if success is true it does not mean that the delete was successful, it only means that the ajax call
76
     * was successful.
77
     *
78
     * Example:
79
     *
80
     * ```
81
     *  [
82
     *     'class'=> ToggleColumn::className(),
83
     *     'afterToggle'=>'function(success, data){ if (success) alert("Toggled successfully"); }',
84
     *  ],
85
     * ```
86
     */
87
    public $afterToggle;
88
    /**
89
     * @var string suffix substituted to a name class of the tag <a>
90
     */
91
    public $classSuffix;
92
93
    /**
94
     * @inheritdoc
95
     * @throws \yii\base\InvalidConfigException
96
     */
97
    public function init()
98
    {
99
        if ($this->url === null) {
100
            throw new InvalidConfigException("'Url' property must be specified.");
101
        }
102
103
        parent::init();
104
        Html::addCssClass($this->headerOptions, 'toggle-column');
105
        Html::addCssClass($this->footerOptions, 'toggle-column');
106
        $this->format = 'raw';
107
        $this->onLabel = $this->onLabel ?: Yii::t('app', 'On');
108
        $this->offLabel = $this->offLabel ?: Yii::t('app', 'Off');
109
        $this->emptyLabel = $this->emptyLabel ?: Yii::t('app', 'Not set');
110
        $this->registerClientScript();
111
    }
112
113
    /**
114
     * @inheritdoc
115
     */
116
    public function renderDataCell($model, $key, $index)
117
    {
118
        if ($this->contentOptions instanceof \Closure) {
119
            $options = call_user_func($this->contentOptions, $model, $key, $index, $this);
120
        } else {
121
            $options = $this->contentOptions;
122
        }
123
        Html::addCssClass($options, 'toggle-column');
124
125
        return Html::tag('td', $this->renderDataCellContent($model, $key, $index), $options);
126
    }
127
128
    /**
129
     * @inheritdoc
130
     */
131
    protected function renderDataCellContent($model, $key, $index)
132
    {
133
        $value = parent::renderDataCellContent($model, $key, $index);
134
135
        $options = ['class' => $this->attribute . '_toggle' . $this->classSuffix, 'data-pjax' => '0'];
136
137
        $url = $this->url;
138
139
        if (isset($url)) {
140
            if ($model instanceof Model) {
141
                $keys = $model->primaryKey();
142
                $key = $keys[0];
143
            }
144
145
            $url = (array)$this->url;
146
            $url['attribute'] = $this->attribute;
147
            $url['id'] = ($model instanceof Model)
148
                ? $model->getPrimaryKey()
149
                : $key;
150
            $url = Url::to($url);
151
        }
152
153
        if (!$this->asText) {
154
            $text = $value === null ? $this->emptyIcon : ($value === $this->onValue ? $this->onIcon : $this->offIcon);
155
            $text = Html::tag('span', '', ['class' => $text]);
156
            $options['title'] = $this->getToggleText($value);
157
            $options['rel'] = 'tooltip';
158
        } else {
159
            $text = $this->getToggleText($value);
160
        }
161
162
        return Html::a($text, $url, $options);
163
    }
164
165
    /**
166
     * @param $value
167
     *
168
     * @return string
169
     */
170
    protected function getToggleText($value)
171
    {
172
        return $value === null ? $this->emptyLabel : ($value === $this->onValue ? $this->onLabel : $this->offLabel);
173
    }
174
175
    /**
176
     * Registers the required scripts for the toggle column to work properly
177
     */
178
    protected function registerClientScript()
179
    {
180
        $view = $this->grid->getView();
181
182
        ToggleColumnAsset::register($view);
183
        $grid = $this->grid->id;
184
        $selector = "#$grid a.{$this->attribute}_toggle$this->classSuffix";
185
        $callback = $this->afterToggle ?: 'function(){}';
186
187
        $onText = $this->asText ? $this->onLabel : Html::tag('span', '', ['class' => $this->onIcon]);
188
        $offText = $this->asText ? $this->offLabel : Html::tag('span', '', ['class' => $this->offIcon]);
189
190
        $js = [];
191
        $js[] = "dosamigos.toggleColumn.onText='{$onText}'";
192
        $js[] = "dosamigos.toggleColumn.offText='{$offText}'";
193
        $js[] = "dosamigos.toggleColumn.onTitle='{$this->onLabel}'";
194
        $js[] = "dosamigos.toggleColumn.offTitle='{$this->offLabel}'";
195
        $js[] = "dosamigos.toggleColumn.registerHandler('$grid','$selector', $callback);";
196
197
        $view->registerJs(implode("\n", $js));
198
    }
199
}
200