Skip to content

Commit 68cfa2d

Browse files
committed
Merge pull request #5 from AntonYu/button-var
Added optional variable for clicked button, accessible from callbacks.
2 parents b0a8d2c + 895e157 commit 68cfa2d

File tree

1 file changed

+13
-6
lines changed

1 file changed

+13
-6
lines changed

AjaxSubmitButton.php

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
use yii\base\Widget;
55
use yii\helpers\Html;
66
use yii\helpers\Json;
7+
use yii\web\JsExpression;
78

89
/**
910
* AjaxSubmitButton renders an ajax button which is very similar to ajaxSubmitButton from Yii1.
@@ -66,12 +67,15 @@ class AjaxSubmitButton extends Widget
6667
*/
6768
public $encodeLabel = true;
6869

70+
public $clickedButtonVarName = '_clickedButton';
71+
6972
/**
7073
* Initializes the widget.
7174
*/
7275
public function init()
7376
{
7477
parent::init();
78+
7579
if (!isset($this->options['id'])) {
7680
$this->options['id'] = $this->getId();
7781
}
@@ -83,30 +87,33 @@ public function run()
8387

8488
echo Html::tag($this->tagName, $this->encodeLabel ? Html::encode($this->label) : $this->label, $this->options);
8589

86-
if (!empty($this->ajaxOptions))
90+
if (!empty($this->ajaxOptions)) {
8791
$this->registerAjaxScript();
92+
}
8893
}
8994

9095
protected function registerAjaxScript()
9196
{
9297
$view = $this->getView();
9398

9499
if(!isset($this->ajaxOptions['type'])) {
95-
$this->ajaxOptions['type'] = new \yii\web\JsExpression('$(this).parents("form").attr("method")');
100+
$this->ajaxOptions['type'] = new JsExpression('$(this).parents("form").attr("method")');
96101
}
97102

98103
if(!isset($this->ajaxOptions['url'])) {
99-
$this->ajaxOptions['url'] = new \yii\web\JsExpression('$(this).parents("form").attr("action")');
104+
$this->ajaxOptions['url'] = new JsExpression('$(this).parents("form").attr("action")');
100105
}
101106

102107
if(!isset($this->ajaxOptions['data']) && isset($this->ajaxOptions['type']))
103-
$this->ajaxOptions['data'] = new \yii\web\JsExpression('$(this).parents("form").serialize()');
108+
$this->ajaxOptions['data'] = new JsExpression('$(this).parents("form").serialize()');
104109

105110
$this->ajaxOptions= Json::encode($this->ajaxOptions);
106-
$view->registerJs("$( '#".$this->options['id']."' ).click(function() {
107-
$.ajax(". $this->ajaxOptions .");
111+
$view->registerJs("$('#".$this->options['id']."').click(function() {
112+
" . (null !== $this->clickedButtonVarName ? "var {$this->clickedButtonVarName} = this;" : "") . "
113+
$.ajax(" . $this->ajaxOptions . ");
108114
return false;
109115
});");
110116
}
111117

112118
}
119+

0 commit comments

Comments
 (0)