Passed
Push — master ( 5d7723...f7e125 )
by Paweł
03:17
created

AjaxButton   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 46
rs 10
c 0
b 0
f 0
wmc 3

2 Methods

Rating   Name   Duplication   Size   Complexity  
A registerClientScripts() 0 23 1
A run() 0 10 2
1
<?php
2
/**
3
 * Created for IG Monitoring.
4
 * User: jakim <[email protected]>
5
 * Date: 04.05.2018
6
 */
7
8
namespace app\components;
9
10
11
use yii\base\Widget;
12
use yii\helpers\Html;
13
use yii\helpers\Json;
14
use yii\helpers\Url;
15
16
class AjaxButton extends Widget
17
{
18
    public $tag = 'a';
19
    public $text;
20
    public $url;
21
    public $options = ['class' => 'btn btn-link'];
22
    public $method = 'post';
23
    public $data = [];
24
    public $confirm;
25
    public $successCallback;
26
27
    public function run()
28
    {
29
        $options = $this->options;
30
        if (!isset($options['id'])) {
31
            $options['id'] = $this->getId();
32
        }
33
34
        echo Html::tag($this->tag, $this->text, $options);
35
36
        $this->registerClientScripts();
37
    }
38
39
    protected function registerClientScripts()
40
    {
41
        $options = [
42
            'url' => Url::to($this->url),
43
            'method' => $this->method,
44
            'data' => $this->data,
45
            'success' => $this->successCallback,
46
        ];
47
        $options = Json::encode($options);
48
49
        $js = <<<JS
50
jQuery('#{$this->getId()}').click(function(e){
51
    e.preventDefault();
52
    if ("{$this->confirm}"){
53
        if(confirm("{$this->confirm}")){
54
            jQuery.ajax($options);         
55
        }
56
    }else{
57
        jQuery.ajax($options);
58
    } 
59
});
60
JS;
61
        $this->view->registerJs($js);
62
    }
63
}