44use yii \base \Widget ;
55use yii \helpers \Html ;
66use 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