AmountWithCurrency::initClientScript()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 12
ccs 0
cts 0
cp 0
rs 9.8666
cc 1
nc 1
nop 0
crap 2
1
<?php
2
/**
3
 * HiPanel core package
4
 *
5
 * @link      https://hipanel.com/
6
 * @package   hipanel-core
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2014-2019, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\widgets;
12
13
use yii\helpers\Html;
14
use yii\widgets\InputWidget;
15
16
class AmountWithCurrency extends InputWidget
17
{
18
    public static $widgetClass = 'amount-with-currency-widget';
19
20
    /**
21
     * @var string Set this value to use it instead of model currency value
22
     */
23
    public $selectedCurrencyCode;
24
    public $currencyAttributeName;
25
    public $currencyAttributeOptions;
26
    /**
27
     * @var array The following keys are used:
28
     *
29
     * - `readonly`: protects currency input from changes
30
     * - `hidden`: hides the dropdown button and leave only currency symbol
31
     */
32
    public $currencyDropdownOptions = [];
33
34
    public function init()
35
    {
36
        parent::init();
37
38
        $this->options = array_merge(['class' => 'form-control'], $this->options);
39
    }
40
41
    public function run()
42
    {
43
        $this->initClientScript();
44
45
        return $this->render((new \ReflectionClass($this))->getShortName(), [
46
            'containerClass' => self::$widgetClass,
47
48
            'form' => $this->field->form,
49
            'model' => $this->model,
50
            'attribute' => $this->attribute,
51
52
            'selectedCurrencyCode' => $this->getSelectedCurrencyCode(),
53
            'currencyAttributeOptions' => $this->currencyAttributeOptions,
54
            'currencyDropdownOptions' => $this->currencyDropdownOptions,
55
        ]);
56
    }
57
58
    public function initClientScript()
59
    {
60
        $widgetClass = self::$widgetClass;
61
        $this->getView()->registerJs(<<<"JS"
62
        $(document).on('click', '.{$widgetClass} a', function(e) {
63
            var item = $(this);
64
            item.parents('.amount-with-currency-widget').find('.iwd-label').text(item.data('label'));
65
            item.parents('.amount-with-currency-widget').find(':hidden').val(item.data('value')).trigger('change');
66
        });
67
JS
68
        );
69
    }
70
71
    private function getSelectedCurrencyCode()
72
    {
73
        return $this->selectedCurrencyCode ?: Html::getAttributeValue($this->model, $this->currencyAttributeName);
74
    }
75
}
76