AskToSaveWork   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
c 1
b 0
f 0
lcom 1
cbo 3
dl 0
loc 31
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 6 2
A registerAssets() 0 10 1
1
<?php
2
3
namespace cornernote\dashboard\widgets;
4
5
use Yii;
6
use yii\web\View;
7
use yii\base\Widget;
8
9
/**
10
 * AskToSaveWork
11
 *
12
 * Asks for a confirmation before leaving the page after they make a change to the form.
13
 *
14
 * USAGE:
15
 * ```
16
 * AskToSaveWork::widget([
17
 *     'message' => Yii::t('app', 'Please save before leaving this page.'),
18
 * ]);
19
 * ```
20
 */
21
class AskToSaveWork extends Widget
22
{
23
    /**
24
     * @var String Message to show to user preventing exit the page
25
     */
26
    public $message;
27
28
    /**
29
     * @inheritdoc
30
     */
31
    public function init()
32
    {
33
        parent::init();
34
        $this->message = isset($this->message) ? $this->message : Yii::t('dashboard', 'Please save before leaving this page.');
35
        $this->registerAssets();
36
    }
37
38
    /**
39
     * @inheritdoc
40
     */
41
    public function registerAssets()
42
    {
43
        $js = "var formModified = false;";
44
        $this->getView()->registerJs($js, View::POS_END);
45
46
        $js = "$('form :input').change(function(){ formModified=true; });";
47
        $js .= "$(window).bind('beforeunload', function() { if (formModified) { return \"" . $this->message . "\"; } });";
48
        $js .= "$(':submit').bind('click', function(){ formModified=false; });";
49
        $this->getView()->registerJs($js);
50
    }
51
}