Completed
Push — master ( 422d4b...f2a219 )
by Dmitry
07:23
created

BulkAssignmentFieldsLinker::run()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 0
1
<?php
2
3
namespace hipanel\widgets;
4
5
use yii\base\Widget;
6
use yii\helpers\Json;
7
8
/**
9
 * Class BulkAssignmentFieldsLinker registers JS to link
10
 * inputs in bulk assignment form in order to copy value
11
 * from the first input to all the inputs bellow.
12
 *
13
 * @author Dmytro Naumenko <[email protected]>
14
 */
15
class BulkAssignmentFieldsLinker extends Widget
16
{
17
    public $inputSelectors = [];
18
19
    public function run()
20
    {
21
        foreach ($this->inputSelectors as $selector) {
22
            $this->registerClientScriptFor($selector);
23
        }
24
    }
25
26
    protected function registerClientScriptFor($selector)
27
    {
28
        $selector = Json::htmlEncode($selector);
29
30
        $this->view->registerJs(<<<JS
31
            $({$selector}).on('change', function (event) {
32
                var similar = $(this).closest('form').find($selector),
33
                    value = $(this).val();
34
35
                if (this !== similar[0]) {
36
                    return;
37
                }
38
39
                if ($(this).data('field')) {
40
                    value = $(this).data('field').getData();
41
                    var isCombo = true;
42
                }
43
44
                similar.slice(1).each(function() {
45
                    if (isCombo) {
46
                        $(this).data('field').setData(value, true);
47
                    } else {
48
                        $(this).val(value).trigger('change');
49
                    }
50
                });
51
            });
52
JS
53
        );
54
    }
55
}
56