Completed
Push — master ( 8e4a64...521cc3 )
by Paweł
04:47
created

AjaxButton::run()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 11
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created for IG Monitoring.
4
 * User: jakim <[email protected]>
5
 * Date: 10.07.2018
6
 */
7
8
namespace app\modules\admin\widgets;
9
10
11
use yii\base\Widget;
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\Html;
14
use yii\helpers\Json;
15
use yii\helpers\Url;
16
use yii\web\JsExpression;
17
18
class AjaxButton extends Widget
19
{
20
    public $confirm = false;
21
    public $confirmMessage = 'Are you sure?';
22
    public $successCallback;
23
    public $data = [];
24
25
    public $text = 'Update';
26
    public $url;
27
28
    public $tag = 'a';
29
    public $options = [
30
        'class' => 'btn btn-success',
31
        'data' => [
32
            'style' => 'zoom-out',
33
        ],
34
    ];
35
    public $ajaxOptions = [];
36
37
    public function init()
38
    {
39
        parent::init();
40
41
        $this->confirm = Json::encode($this->confirm);
42
        $this->successCallback = $this->successCallback ?: new JsExpression('function(data){if(typeof data === \'string\' || data instanceof String){window.location.replace(data);}else{location.reload();}}');
43
44
        $this->setId('ab-' . $this->getId());
45
        $this->view->registerCssFile('https://cdnjs.cloudflare.com/ajax/libs/Ladda/1.0.6/ladda-themeless.min.css');
46
        $this->view->registerJsFile('https://cdnjs.cloudflare.com/ajax/libs/Ladda/1.0.6/spin.min.js');
47
        $this->view->registerJsFile('https://cdnjs.cloudflare.com/ajax/libs/Ladda/1.0.6/ladda.min.js');
48
    }
49
50
    public function run()
51
    {
52
        $options = $this->options;
53
        if (!isset($options['id'])) {
54
            $options['id'] = $this->getId();
55
        }
56
        Html::addCssClass($options, 'ladda-button');
57
58
        echo Html::tag($this->tag, $this->text, $options);
59
60
        $this->registerClientScript();
61
    }
62
63
    protected function registerClientScript()
64
    {
65
        $options = ArrayHelper::merge([
66
            'url' => Url::to($this->url),
67
            'method' => 'post',
68
            'data' => $this->data,
69
            'success' => $this->successCallback,
70
        ], $this->ajaxOptions);
71
        $options = Json::encode($options);
72
73
        $r = <<<JS
74
var l = Ladda.create(this);
75
l.start();
76
jQuery.ajax($options)
77
.always(function() { l.stop(); });         
78
JS;
79
80
        $js = <<<JS
81
jQuery('#{$this->getId()}').click(function(e){
82
    e.preventDefault();
83
    if ({$this->confirm}){
84
        if(confirm("{$this->confirmMessage}")){$r}
85
    }else{
86
        $r
87
    } 
88
});
89
JS;
90
        $this->view->registerJs($js);
91
    }
92
}