forked from vitalets/x-editable-yii
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEditable.php
749 lines (673 loc) · 24.7 KB
/
Editable.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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
<?php
/**
* Editable class file.
*
* @author Vitaliy Potapov <noginsk@rambler.ru>
* @link https://github.com/vitalets/x-editable-yii
* @copyright Copyright © Vitaliy Potapov 2012
* @version 1.3.0
*/
/**
* Editable widget creates editable element on page (without linking to model attribute).
*
* @package widgets
*/
class Editable extends CWidget
{
//note: only most usefull options are on first level of config.
// --- start of X-editable options ----
/**
* @var string type of editable widget. Can be `text`, `textarea`, `select`, `date`, `checklist`, etc.
* @see x-editable
*/
public $type = null;
/**
* @var string url to submit value. Can be string or array containing Yii route, e.g. `array('site/updateUser')`
* @see x-editable
*/
public $url = null;
/**
* @var mixed primary key
* @see x-editable
*/
public $pk = null;
/**
* @var array additional data to send to server via get to source url requets
*/
public $additional_data=null;
/**
* @var string name of field
* @see x-editable
*/
public $name = null;
/**
* @var array additional params to send on server
* @see x-editable
*/
public $params = null;
/**
* @var string css class of input. If `null` - default X-editable value is used: `input-medium`
* @see x-editable
*/
public $inputclass = null;
/**
* @var string mode of input: `inline` | `popup`. If not set - default X-editable value is used: `popup`.
* @see x-editable
*/
public $mode = null;
/**
* @var string text to be shown as element content
*/
public $text = null;
/**
* @var mixed initial value. If not set - will be taken from text
* @see x-editable
*/
public $value = null;
/**
* @var string placement of popup. Can be `left`, `top`, `right`, `bottom`. If `null` - default X-editable value is used: `top`
* @see x-editable
*/
public $placement = null;
/**
* @var string text shown on empty field. If `null` - default X-editable value is used: `Empty`
* @see x-editable
*/
public $emptytext = null;
/**
* @var string visibility of buttons. Can be boolean `false|true` or string `bottom`.
* @see x-editable
*/
public $showbuttons = null;
/**
* @var boolean will editable be initially disabled. It means editable plugin will be applied to element,
* but you should call `.editable('enable')` method to activate it.
* To totally disable applying 'editable' to element use **apply** option.
* @see x-editable
*/
public $disabled = false;
//list
/**
* @var mixed source data for **select**, **checklist**. Can be string (url) or array in format:
* array( array("value" => 1, "text" => "abc"), ...)
* @package list
* @see x-editable
*/
public $source = null;
//date
/**
* @var string format to send date on server. If `null` - default X-editable value is used: `yyyy-mm-dd`.
* @package date
* @see x-editable
*/
public $format = null;
/**
* @var string format to display date in element. If `null` - equals to **format** option.
* @package date
* @see x-editable
*/
public $viewformat = null;
/**
* @var string template for **combodate** input. For details see http://vitalets.github.com/x-editable/docs.html#combodate.
* @package combodate
* @see x-editable
*/
public $template = null;
/**
* @var array full config for **combodate** input. For details see http://vitalets.github.com/combodate/#docs
* @package combodate
* @see x-editable
*/
public $combodate = null;
/**
* @var string separator used to display tags.
* @package select2
* @see x-editable
*/
public $viewseparator = null;
/**
* @var array full config for **select2** input. For details see http://ivaynberg.github.com/select2
* @package select2
* @see x-editable
*/
public $select2 = null;
//methods
/**
* A javascript function that will be invoked to validate value.
* Example:
* <pre>
* 'validate' => 'js: function(value) {
* if($.trim(value) == "") return "This field is required";
* }'
* </pre>
*
* @var string
* @package callback
* @see x-editable
* @example
*/
public $validate = null;
/**
* A javascript function that will be invoked to process successful server response.
* Example:
* <pre>
* 'success' => 'js: function(response, newValue) {
* if(!response.success) return response.msg;
* }'
* </pre>
*
* @var string
* @package callback
* @see x-editable
*/
public $success = null;
/**
* A javascript function that will be invoked to custom display value.
* Example:
* <pre>
* 'display' => 'js: function(value, sourceData) {
* var escapedValue = $("<div>").text(value).html();
* $(this).html("<b>"+escapedValue+"</b>");
* }'
* </pre>
*
* @var string
* @package callback
* @see x-editable
*/
public $display = null;
/**
* DOM id of target where afterAjaxUpdate handler will call
* live update of editable element
*
* @var string
*/
public $liveTarget = null;
/**
* jQuery selector of elements to wich will be applied editable.
* Usefull in combination of `liveTarget` when you want to keep field(s) editble
* after ajaxUpdate
*
* @var string
*/
public $liveSelector = null;
// --- X-editable events ---
/**
* A javascript function that will be invoked when editable element is initialized
* @var string
* @package event
* @see x-editable
*/
public $onInit;
/**
* A javascript function that will be invoked when editable form is shown
* Example:
* <pre>
* 'onShown' => 'js: function() {
* var $tip = $(this).data("editableContainer").tip();
* $tip.find("input").val("overwriting value of input.");
* }'
* </pre>
*
* @var string
* @package event
* @see x-editable
*/
public $onShown;
/**
* A javascript function that will be invoked when new value is saved
* Example:
* <pre>
* 'onSave' => 'js: function(e, params) {
* alert("Saved value: " + params.newValue);
* }'
* </pre>
*
* @var string
* @package event
* @see x-editable
*/
public $onSave;
/**
* A javascript function that will be invoked when editable form is hidden
* Example:
* <pre>
* 'onHidden' => 'js: function(e, reason) {
* if(reason === "save" || reason === "cancel") {
* //auto-open next editable
* $(this).closest("tr").next().find(".editable").editable("show");
* }
* }'
* </pre>
*
* @var string
* @package event
* @see x-editable
*/
public $onHidden;
/**
* @var array all config options of x-editable. See full list <a href="http://vitalets.github.com/x-editable/docs.html#editable">here</a>.
*/
public $options = array();
/**
* @var array HTML options of element
*/
public $htmlOptions = array();
/**
* @var boolean whether to HTML encode text on output
*/
public $encode = true;
/**
* @var boolean whether to apply 'editable' js plugin to element.
* Only **safe** attributes become editable.
*/
public $apply = null;
/**
* @var string title of popup. If `null` - will be generated automatically from attribute label.
* Can have token {label} inside that will be replaced with actual attribute label.
*/
public $title = null;
//themeUrl, theme and cssFile copied from CJuiWidget to allow include custom theme for jQuery UI
/**
* @var string for jQuery UI only. The root URL that contains JUI theme folders.
* If not set, default Yii's theme will be used.
*/
public $themeUrl;
/**
* @var string for jQuery UI only. The JUI theme name.
*/
public $theme='base';
/**
* @var mixed for jQuery UI only. The theme CSS file name. By default Yii's jquery UI css used.
*/
public $cssFile='jquery-ui.css';
protected $_prepareToAutotext = false;
/**
* initialization of widget
*
*/
public function init()
{
parent::init();
if (!$this->name) {
throw new CException('Parameter "name" should be provided for Editable widget');
}
/*
If set this flag to true --> element content will stay empty
and value will be rendered to data-value attribute to apply autotext afterwards.
*/
$this->_prepareToAutotext = self::isAutotext($this->options, $this->type);
}
public function buildHtmlOptions()
{
//html options
$htmlOptions = array(
'href' => '#',
'rel' => $this->liveSelector ? $this->liveSelector : $this->getSelector(),
);
//set data-pk
if($this->pk !== null) {
$htmlOptions['data-pk'] = is_array($this->pk) ? CJSON::encode($this->pk) : $this->pk;
}
// set additional_data
if($this->additional_data && is_array($this->additional_data))
{
foreach($this->additional_data as $data_key => $data_value)
{
$htmlOptions['data-'.$data_key] = is_array($data_value) ? CJSON::encode($data_value) : $data_value;
}
}
//if input type assumes autotext (e.g. select) we define value directly in data-value
//and do not fill element contents
if ($this->_prepareToAutotext) {
//for date we use 'format' to put it into value (if text not defined)
if ($this->type == 'date') {
//if date comes as object, format it to string
if($this->value instanceOf DateTime || is_long($this->value)) {
/*
* unfortunatly datepicker's format does not match Yii locale dateFormat,
* we need replacements below to convert date correctly
*/
$count = 0;
$format = str_replace('MM', 'MMMM', $this->format, $count);
if(!$count) $format = str_replace('M', 'MMM', $format, $count);
if(!$count) $format = str_replace('m', 'M', $format);
if($this->value instanceof DateTime) {
$timestamp = $this->value->getTimestamp();
} else {
$timestamp = $this->value;
}
$this->value = Yii::app()->dateFormatter->format($format, $timestamp);
}
}
if(is_scalar($this->value)) {
$this->htmlOptions['data-value'] = $this->value;
}
//if not scalar, value will be added to js options instead of html options
}
//merging options
$this->htmlOptions = CMap::mergeArray($this->htmlOptions, $htmlOptions);
}
public function buildJsOptions()
{
//normalize url from array
$this->url = CHtml::normalizeUrl($this->url);
$options = array(
'name' => $this->name,
'title' => CHtml::encode($this->title),
);
//if value needed for autotext and it's not scalar --> add it to js options
if ($this->_prepareToAutotext && !is_scalar($this->value)) {
$options['value'] = $this->value;
}
//support of CSRF out of box, see https://github.com/vitalets/x-editable-yii/issues/38
if (Yii::app()->request->enableCsrfValidation) {
$csrfTokenName = Yii::app()->request->csrfTokenName;
$csrfToken = Yii::app()->request->csrfToken;
if(!isset($this->params[$csrfTokenName])) {
$this->params[$csrfTokenName] = $csrfToken;
}
}
//simple options set directly from config
foreach(array('url', 'type', 'mode', 'placement', 'emptytext', 'params', 'inputclass', 'format', 'viewformat', 'template',
'combodate', 'select2', 'viewseparator', 'showbuttons'
) as $option) {
if ($this->$option !== null) {
$options[$option] = $this->$option;
}
}
if ($this->source) {
//if source is array --> convert it to x-editable format.
//Since 1.1.0 source as array with one element is NOT treated as Yii route!
if(is_array($this->source)) {
//if first elem is array assume it's normal x-editable format, so just pass it
if(isset($this->source[0]) && is_array($this->source[0])) {
$options['source'] = $this->source;
} else { //else convert to x-editable source format {value: 1, text: 'abc'}
$options['source'] = array();
foreach($this->source as $value => $text) {
$options['source'][] = array('value' => $value, 'text' => $text);
}
}
} else { //source is url string (or js function)
$options['source'] = CHtml::normalizeUrl($this->source);
}
}
//callbacks
foreach(array('validate', 'success', 'display') as $method) {
if(isset($this->$method)) {
$options[$method]=(strpos($this->$method, 'js:') !== 0 ? 'js:' : '') . $this->$method;
}
}
//merging options
$this->options = CMap::mergeArray($this->options, $options);
}
public function registerClientScript()
{
$selector = "a[rel=\"{$this->htmlOptions['rel']}\"]";
if($this->liveTarget) {
$selector = '#'.$this->liveTarget.' '.$selector;
}
$script = "$('".$selector."')";
//attach events
foreach(array('init', 'shown', 'save', 'hidden') as $event) {
$eventName = 'on'.ucfirst($event);
if (isset($this->$eventName)) {
// CJavaScriptExpression appeared only in 1.1.11, will turn to it later
//$event = ($this->onInit instanceof CJavaScriptExpression) ? $this->onInit : new CJavaScriptExpression($this->onInit);
$eventJs = (strpos($this->$eventName, 'js:') !== 0 ? 'js:' : '') . $this->$eventName;
$script .= "\n.on('".$event."', ".CJavaScript::encode($eventJs).")";
}
}
//apply editable
$options = CJavaScript::encode($this->options);
$script .= ".editable($options);";
//wrap in anonymous function for live update
if($this->liveTarget) {
$script .= "\n $('body').on('ajaxUpdate.editable', function(e){ if(e.target.id == '".$this->liveTarget."') yiiEditable(); });";
$script = "(function yiiEditable() {\n ".$script."\n}());";
}
Yii::app()->getClientScript()->registerScript(__CLASS__ . '-' . $selector, $script);
return $script;
}
public function registerAssets()
{
$am = Yii::app()->getAssetManager();
$cs = Yii::app()->getClientScript();
$form = yii::app()->editable->form;
$mode = $this->mode ? $this->mode : yii::app()->editable->defaults['mode'];
// bootstrap
if($form === EditableConfig::FORM_BOOTSTRAP) {
if (($bootstrap = yii::app()->getComponent('bootstrap'))) {
$bootstrap->registerCoreCss();
$bootstrap->registerCoreScripts();
} else {
throw new CException('You need to setup Yii-bootstrap extension first.');
}
$assetsUrl = $am->publish(Yii::getPathOfAlias('editable.assets.bootstrap-editable'));
$js = 'bootstrap-editable.js';
$css = 'bootstrap-editable.css';
// jqueryui
} elseif($form === EditableConfig::FORM_JQUERYUI) {
if($mode === EditableConfig::POPUP && Yii::getVersion() < '1.1.13' ) {
throw new CException('jQuery UI editable popup supported from Yii 1.1.13+');
}
//register jquery ui
$this->registerJQueryUI();
$assetsUrl = $am->publish(Yii::getPathOfAlias('editable.assets.jqueryui-editable'));
$js = 'jqueryui-editable.js';
$css = 'jqueryui-editable.css';
// plain jQuery
} else {
$assetsUrl = $am->publish(Yii::getPathOfAlias('editable.assets.jquery-editable'));
$js = 'jquery-editable-poshytip.js';
$css = 'jquery-editable.css';
//publish & register poshytip for popup version
if($mode === EditableConfig::POPUP) {
$poshytipUrl = $am->publish(Yii::getPathOfAlias('editable.assets.poshytip'));
$cs->registerScriptFile($poshytipUrl . '/jquery.poshytip.js');
$cs->registerCssFile($poshytipUrl . '/tip-yellowsimple/tip-yellowsimple.css');
}
//register jquery ui for datepicker
if($this->type == 'date' || $this->type == 'dateui') {
$this->registerJQueryUI();
}
}
//register assets
$cs->registerCssFile($assetsUrl.'/css/'.$css);
$cs->registerScriptFile($assetsUrl.'/js/'.$js, CClientScript::POS_END);
//include moment.js for combodate
if($this->type == 'combodate') {
$momentUrl = $am->publish(Yii::getPathOfAlias('editable.assets.moment'));
$cs->registerScriptFile($momentUrl.'/moment.min.js');
}
//include select2 lib for select2 type
if($this->type == 'select2') {
$select2Url = $am->publish(Yii::getPathOfAlias('editable.assets.select2'));
$cs->registerScriptFile($select2Url.'/select2.min.js');
$cs->registerCssFile($select2Url.'/select2.css');
}
//include bootstrap-datetimepicker
if($this->type == 'datetime') {
$url = $am->publish(Yii::getPathOfAlias('editable.assets.bootstrap-datetimepicker'));
$cs->registerScriptFile($url.'/js/bootstrap-datetimepicker.js');
$cs->registerCssFile($url.'/css/datetimepicker.css');
}
//TODO: include locale for datepicker
//may be do it manually?
/*
if ($this->type == 'date' && $this->language && substr($this->language, 0, 2) != 'en') {
//todo: check compare dp locale name with yii's
$localesUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('ext.editable.assets.js.locales'));
Yii::app()->clientScript->registerScriptFile($localesUrl . '/bootstrap-datepicker.'. str_replace('_', '-', $this->language).'.js', CClientScript::POS_END);
}
*/
}
public function run()
{
//Register script (even if apply = false to support live update)
if($this->apply !== false || $this->liveTarget) {
$this->buildHtmlOptions();
$this->buildJsOptions();
$this->registerAssets();
$this->registerClientScript();
}
if($this->apply !== false) {
$this->renderLink();
} else {
$this->renderText();
}
}
public function renderLink()
{
echo CHtml::openTag('a', $this->htmlOptions);
$this->renderText();
echo CHtml::closeTag('a');
}
public function renderText()
{
$encodedText = $this->encode ? CHtml::encode($this->text) : $this->text;
if($this->type == 'textarea') {
$encodedText = preg_replace('/\r?\n/', '<br>', $encodedText);
}
echo $encodedText;
}
public function getSelector()
{
//for live updates selectorshould not contain pk
if($this->liveTarget) {
return $this->name;
}
$pk = $this->pk;
if($pk === null) {
$pk = 'new';
} else {
//support of composite keys: convert to string: e.g. 'id-1_lang-ru'
if(is_array($pk)) {
//below not works in PHP < 5.3, see https://github.com/vitalets/x-editable-yii/issues/39
//$pk = join('_', array_map(function($k, $v) { return $k.'-'.$v; }, array_keys($pk), $pk));
$buffer = array();
foreach($pk as $k => $v) {
$buffer[] = $k.'-'.$v;
}
$pk = join('_', $buffer);
}
}
return $this->name.'_'.$pk;
}
/**
* Returns is autotext should be applied to widget:
* e.g. for 'select' to display text for id
*
* @param mixed $options
* @param mixed $type
*/
public static function isAutotext($options, $type)
{
return (!isset($options['autotext']) || $options['autotext'] !== 'never')
&& in_array($type, array(
'select',
'checklist',
'date',
'datetime',
'dateui',
'combodate',
'select2'
));
}
/**
* Returns php-array as valid x-editable source in format:
* [{value: 1, text: 'text1'}, {...}]
*
* See https://github.com/vitalets/x-editable-yii/issues/37
*
* @param mixed $models
* @param mixed $valueField
* @param mixed $textField
* @param mixed $groupField
* @param mixed $groupTextField
*/
public static function source($models, $valueField='', $textField='', $groupField='', $groupTextField='')
{
$listData=array();
$first = reset($models);
//simple 1-dimensional array: 0 => 'text 0', 1 => 'text 1'
if($first && (is_string($first) || is_numeric($first))) {
foreach($models as $key => $text) {
$listData[] = array('value' => $key, 'text' => $text);
}
return $listData;
}
// 2-dimensional array or dataset
if($groupField === '') {
foreach($models as $model) {
$value = CHtml::value($model, $valueField);
$text = CHtml::value($model, $textField);
$listData[] = array('value' => $value, 'text' => $text);
}
} else {
if(!$groupTextField) {
$groupTextField = $groupField;
}
$groups = array();
foreach($models as $model) {
$group=CHtml::value($model,$groupField);
$groupText=CHtml::value($model,$groupTextField);
$value=CHtml::value($model,$valueField);
$text=CHtml::value($model,$textField);
if($group === null) {
$listData[] = array('value' => $value, 'text' => $text);
} else {
if(!isset($groups[$group])) {
$groups[$group] = array('value' => $group, 'text' => $groupText, 'children' => array(), 'index' => count($listData));
$listData[] = 'group'; //placeholder, will be replaced in future
}
$groups[$group]['children'][] = array('value' => $value, 'text' => $text);
}
}
//fill placeholders with group data
foreach($groups as $group) {
$index = $group['index'];
unset($group['index']);
$listData[$index] = $group;
}
}
return $listData;
}
/**
* injects ajaxUpdate event into widget
*
* @param mixed $widget
*/
public static function attachAjaxUpdateEvent($widget)
{
$trigger = '$("#'.$widget->id.'").trigger("ajaxUpdate.editable");';
//check if trigger already inserted by another column
if(strpos($widget->afterAjaxUpdate, $trigger) !== false) return;
//inserting trigger
if(strlen($widget->afterAjaxUpdate)) {
$orig = $widget->afterAjaxUpdate;
if(strpos($orig, 'js:')===0) $orig = substr($orig,3);
$orig = "\n($orig).apply(this, arguments);";
} else {
$orig = '';
}
$widget->afterAjaxUpdate = "js: function(id, data) {
$trigger $orig
}";
$widget->registerClientScript();
}
/**
* method to register jQuery UI with build-in or custom theme
*
*/
protected function registerJQueryUI()
{
$cs=Yii::app()->getClientScript();
if($this->themeUrl===null) {
$this->themeUrl=$cs->getCoreScriptUrl().'/jui/css';
}
$cs->registerCssFile($this->themeUrl.'/'.$this->theme.'/'.$this->cssFile);
$cs->registerPackage('jquery.ui');
}
}