/
CustomGridView.php
executable file
·444 lines (391 loc) · 15.5 KB
/
CustomGridView.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
<?php
/**
* Widget CustomGridView
*
* @category Widgets
* @package yupe.modules.yupe.widgets
* @author Yupe Team <team@yupe.ru>
* @license https://github.com/yupe/yupe/blob/master/LICENSE BSD
* @link http://yupe.ru
* @todo можно реализовать мультиекшен на основе вызова
* метода из CustomGridView и обращаться непосредственно
* к модели.
**/
namespace yupe\widgets;
use CHtml;
use Yii;
use yupe\models\Settings;
use CClientScript;
Yii::import('bootstrap.widgets.TbExtendedGridView');
class CustomGridView extends \TbExtendedGridView
{
/**
* model name variable
* @access private
* @see CustomGridView()
* @uses init, returnBootstrapStatusHtml, getUpDownButtons, _updatePageSize
* @var string
*/
private $_modelName;
/**
* @todo if this an unused variable - need to delete it
*/
public $inActiveStatus = 0;
/**
* @todo if this an unused variable - need to delete it
*/
public $activeStatus = 1;
/**
* Field for sorting:
* @uses getUpDownButtons
* @var string
*/
public $sortField = 'sort';
/**
* @todo if this an unused variable - need to delete it
*/
public $showStatusText = false;
/**
* @var array Page sizes available to set for web-user.
*/
public $pageSizes = array(5, 10, 15, 20, 50, 100);
/**
* @var string A name for query parameter, that stores page size specified by web-user.
*/
public $pageSizeVarName = 'pageSize';
/**
* @var bool Whether rendering of page size selector at headline section is available and enabled.
*/
protected $_pageSizesEnabled = false;
/**
* constant of headline positions:
* @uses renderHeadline
* @var string
**/
const HP_LEFT = 'left';
const HP_RIGHT = 'right';
/**
* Value of headlinePosition:
* @uses renderHeadline
* @var string
**/
public $headlinePosition;
public $template = "{headline}\n{summary}\n{items}\n{pager}\n{extendedSummary}\n{multiaction}";
public $ajaxUrl;
/**
* Widget initialization
*
* @return void
*/
public function init()
{
$this->_modelName = $this->dataProvider->modelClass;
$this->headlinePosition = empty($this->headlinePosition) ? self::HP_RIGHT : $this->headlinePosition;
$this->initPageSizes();
$this->ajaxUrl = empty($this->ajaxUrl)
? (array) Yii::app()->controller->action->id
: $this->ajaxUrl;
$this->bulkActions = empty($this->bulkActions) ? array(
'actionButtons' => array(
array(
'id' => 'delete-post',
'buttonType' => 'button',
'type' => 'danger',
'size' => 'small',
'label' => Yii::t('YupeModule.yupe', 'Delete'),
'click' => 'js:function(values){ if(!confirm("' . Yii::t('YupeModule.yupe', 'Do you really want to delete selected elements?') . '")) return false; multiaction("delete", values); }',
),
),
'checkBoxColumnConfig' => array(
'name' => 'id'
)) : $this->bulkActions;
$this->type = empty($this->type) ? 'striped condensed' : $this->type;
$this->bulkActionAlign = 'left';
// live hack before yii 1.1.15 release:
strtolower($this->ajaxType) != 'post' || $this->beforeAjaxUpdate = 'function(id, options) {
options.data = $.extend(options.data, ' . json_encode(
array(
Yii::app()->getRequest()->csrfTokenName => Yii::app()->getRequest()->csrfToken,
)
) . ');
}';
parent::init();
}
/**
* Sets "pageSize" parameter at instance of CPagination which belongs to data provider.
* The value to set or specified by the web-user or taken from the session, where it is being stored when user specifies it.
*
* @return void
*/
protected function initPageSizes()
{
$modSettings = Yii::app()->user->getState(\YWebUser::STATE_MOD_SETTINGS, null);
$pagination = $this->dataProvider->getPagination();
if (
!$this->enablePagination
|| strpos($this->template, '{headline}') === false
|| $pagination === false
) {
$this->_pageSizesEnabled = false;
} else {
$this->_pageSizesEnabled = true;
// Web-user specifies desired page size.
if (($pageSizeFromRequest = Yii::app()->getRequest()->getParam($this->pageSizeVarName)) !== null) {
$pageSizeFromRequest = (int)$pageSizeFromRequest;
// Check whether given page size is valid or use default value
if (in_array($pageSizeFromRequest, $this->pageSizes)) {
$pagination->pageSize = $pageSizeFromRequest;
}
$this->_updatePageSize();
}
// Check for value at session or use default value
elseif(isset($modSettings[strtolower($this->_modelName)]['pageSize'])) {
$pagination->pageSize = $modSettings[strtolower($this->_modelName)]['pageSize'];
}
}
}
/**
* Generates HTML-code for BootStrap-icons switch activity, depending on the current state of the model
* Генерирует HTML-код для BootStrap-иконки переключателя активности в зависимости от текущего состояния модели
*
* By default, the state values:
* 0 - Draft (deactivated)
* 1 - Posted on (activated)
* 2 - In Moderation
*
* @param class $data - a model instance for which generated display the switch
* @param string $statusField -
* @param string $method -
* @param array $icons - an array of names icons statuses
*
* @return string HTML-code for BootStrap-switch icon
*
*/
public function returnBootstrapStatusHtml($data, $statusField = 'status', $method = 'Status', $icons = array('lock', 'ok-sign', 'time'))
{
$funcStatus = 'get' . $method;
$funcStatusList = 'get' . $method . 'List';
$text = method_exists($data, $funcStatus) ? $data->$funcStatus() : '';
$iconStatus = isset($icons[$data->$statusField]) ? $icons[$data->$statusField] : 'question-sign';
$icon = '<i class="icon icon-' . $iconStatus . '" title="' . $text . '"></i>';
if (method_exists($data, $funcStatusList)) {
$statusList = $data->$funcStatusList();
reset($statusList);
$status = key($statusList);
while (list($key,) = each($statusList)) {
if ($key == $data->$statusField) {
$keyNext = key($statusList);
if (is_numeric($keyNext)) {
$status = $keyNext;
break;
}
}
}
$url = Yii::app()->controller->createUrl(
"activate", array(
'model' => $this->_modelName,
'id' => $data->id,
'status' => $status,
'statusField' => $statusField,
)
);
$options = array('onclick' => 'ajaxSetStatus(this, "' . $this->id . '"); return false;');
return CHtml::link($icon, $url, $options);
}
return $icon;
}
/**
* Function for rendering Up/Down buttons:
*
* @param class $data - incomming model instance
*
* @return UpDownLinks
*/
public function getUpDownButtons($data)
{
$downUrlImage = '<i class="icon-circle-arrow-down"></i>';
$upUrlImage = '<i class="icon-circle-arrow-up"></i>';
$urlUp = Yii::app()->controller->createUrl(
"sort", array(
'model' => $this->_modelName,
'id' => $data->id,
'sortField' => $this->sortField,
'direction' => 'up',
)
);
$urlDown = Yii::app()->controller->createUrl(
"sort", array(
'model' => $this->_modelName,
'id' => $data->id,
'sortField' => $this->sortField,
'direction' => 'down',
)
);
$options = array('onclick' => 'ajaxSetSort(this, "' . $this->id . '"); return false;',);
return CHtml::link($upUrlImage, $urlUp, $options) . ' ' . CHtml::link($downUrlImage, $urlDown, $options);
}
/**
* Обновление размера страницы
*
* @return void
*/
protected function _updatePageSize()
{
// имя текущей модели
$modelName = strtolower($this->_modelName);
// Делаем так, ибо при попытке править Yii::app()->session['modSettings'] - получаем ошибку
$sessionSettings = Yii::app()->user->getState(\YWebUser::STATE_MOD_SETTINGS, null);
$currentPageSize = $this->dataProvider->getPagination()->pageSize;
// Если переменная не найдена нужно проверить наличие данных в БД
if (!isset($sessionSettings[$modelName]['pageSize'])) {
$sessionSettings[$modelName] = array();
$setting = Settings::model()->findAllByAttributes(array(
'user_id' => Yii::app()->user->getId(),
'module_id' => $modelName,
'param_name' => 'pageSize',
'type' => Settings::TYPE_USER,
)
);
// Если не найдена запись, создаем
if ($setting === null)
{
$setting = new Settings;
$setting->module_id = $modelName;
$setting->param_name = 'pageSize';
$setting->param_value = $currentPageSize;
$setting->type = Settings::TYPE_USER;
$setting->save();
}
}
// Если информация найдена в сессии и значение отличается
elseif ($currentPageSize !== $sessionSettings[$modelName]['pageSize'])
{
// Обновим запись в базе
$setting = Settings::model()->findByAttributes(
array(
'user_id' => Yii::app()->user->getId(),
'module_id' => $modelName,
'param_name' => 'pageSize',
'type' => Settings::TYPE_USER,
)
);
$setting->param_value = $currentPageSize;
$setting->update();
}
$sessionSettings[$modelName]['pageSize'] = $currentPageSize;
// Перезаписываем сессию
Yii::app()->user->setState(\YWebUser::STATE_MOD_SETTINGS, $sessionSettings);
}
/**
* Headline rendering method
*
* @return void
*/
public function renderHeadline()
{
if (!$this->_pageSizesEnabled) {
return;
}
/** @var $cs CClientScript */
$cs = Yii::app()->getClientScript();
$buttons = array();
$currentPageSize = $this->dataProvider->getPagination()->pageSize;
/* Перебор переключателей: */
foreach ($this->pageSizes as $pageSize)
$buttons[] = array(
'label' => $pageSize,
'active' => $pageSize == $currentPageSize,
'htmlOptions' => array(
'class' => 'pageSize',
'rel' => $pageSize,
),
'url' => '#',
);
/* Установка позиции headline'а: */
$headlinePosition = '';
if (in_array($this->headlinePosition, array('left', 'right'))) {
$headlinePosition = ' style="text-align: ' . $this->headlinePosition . ';" ';
}
echo '<div class="headline" ' . $headlinePosition .' >';
/* Текстовка: */
echo Yii::t('YupeModule.yupe', 'Sort by:') . '<br />';
/* Отрисовываем переключатели PageSize'a: */
$this->widget(
'bootstrap.widgets.TbButtonGroup', array(
'size' => 'small',
'type' => 'action',
'toggle' => 'radio',
'buttons' => $buttons,
)
);
echo '</div>';
echo '<br />';
/* Скрипт передачи PageSize: */
$csrfTokenName = Yii::app()->getRequest()->csrfTokenName;
$csrfToken = Yii::app()->getRequest()->csrfToken;
$csrf = Yii::app()->getRequest()->enableCsrfValidation === false
|| strtolower($this->ajaxType) != 'post'
? ""
: ", '$csrfTokenName':'{$csrfToken}'";
$cs->registerScript(
__CLASS__ . '#' . $this->id . 'ExHeadline',
<<<JS
(function(){
$('body').on('click', '#{$this->getId()} .pageSize', function(event) {
event.preventDefault();
$('#{$this->getId()}').yiiGridView('update',{
// Если в гриде нет записей
// будет вылетать с ошибкой - Uncaught TypeError: Cannot call method 'match' of undefined
// В данном случае необходимо указывать URL.
url: window.location.href,
data: {
'{$this->pageSizeVarName}': $(this).attr('rel')$csrf
}
});
});
})();
JS
, CClientScript::POS_READY
);
}
/**
* Function for rendering multiaction:
*
* JS function variables:
* status - type of action:
* 1 - delete
* -------------------
*
* @return nothing
*/
public function renderMultiaction()
{
$cscript = Yii::app()->getClientScript();
$multiactionUrl = Yii::app()->controller->createUrl('multiaction');
/* Скрипт для мультиекшена: */
$cscript->registerScript(
__CLASS__ . '#' . $this->id . 'ExMultiaction',
'var multiaction = function(action, values) {
var queryString = "";
var url = "'.$multiactionUrl.'";
$.map(values, function(itemInput) {
queryString += ((queryString.length > 0) ? "&" : "") + "items[]=" + $(itemInput).val() ;
});
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: "'.Yii::app()->getRequest()->csrfTokenName.'='.Yii::app()->getRequest()->csrfToken.'&model=' . $this->_modelName . '&do=" + action + "&" + queryString,
success: function(data) {
if (data.result) {
$.fn.yiiGridView.update("'.$this->id.'");
}else{
alert(data.data);
}
},
error: function(data){alert("'.Yii::t('YupeModule.yupe','Error!').'")}
});
}', CClientScript::POS_BEGIN
);
}
}