@@ -66,8 +66,18 @@ class AjaxSubmitButton extends Widget
6666 * @var boolean whether the label should be HTML-encoded.
6767 */
6868 public $ encodeLabel = true ;
69-
69+ /**
70+ * @var string js object name.
71+ * it is unused when useWithActiveForm is enabled
72+ */
7073 public $ clickedButtonVarName = '_clickedButton ' ;
74+ /**
75+ * @var boolean whether the button should not be used with ActiveForm.
76+ * string the id of ActiveForm to use the button with
77+ */
78+ public $ useWithActiveForm = false ;
79+
80+
7181
7282 /**
7383 * Initializes the widget.
@@ -88,7 +98,11 @@ public function run()
8898 echo Html::tag ($ this ->tagName , $ this ->encodeLabel ? Html::encode ($ this ->label ) : $ this ->label , $ this ->options );
8999
90100 if (!empty ($ this ->ajaxOptions )) {
91- $ this ->registerAjaxScript ();
101+
102+ if ($ this ->useWithActiveForm !== false )
103+ $ this ->registerAjaxFormScript ();
104+ else
105+ $ this ->registerAjaxScript ();
92106 }
93107 }
94108
@@ -115,5 +129,37 @@ protected function registerAjaxScript()
115129 }); " );
116130 }
117131
132+ protected function registerAjaxFormScript ()
133+ {
134+ $ view = $ this ->getView ();
135+
136+ if (!isset ($ this ->ajaxOptions ['type ' ])) {
137+ $ this ->ajaxOptions ['type ' ] = new JsExpression ('$(this).attr("method") ' );
138+ }
139+
140+ if (!isset ($ this ->ajaxOptions ['url ' ])) {
141+ $ this ->ajaxOptions ['url ' ] = new JsExpression ('$(this).attr("action") ' );
142+ }
143+
144+ if (!isset ($ this ->ajaxOptions ['data ' ]) && isset ($ this ->ajaxOptions ['type ' ]))
145+ $ this ->ajaxOptions ['data ' ] = new JsExpression ('$(this).serialize() ' );
146+
147+ $ this ->ajaxOptions = Json::encode ($ this ->ajaxOptions );
148+
149+ $ js = <<<SEL
150+ $(document).on('beforeSubmit', "# {$ this ->useWithActiveForm }", function () {
151+ if ($(this).find('.has-error').length < 1) {
152+ $.ajax( {$ this ->ajaxOptions });
153+ }
154+ return false; // Cancel form submitting.
155+ });
156+ SEL ;
157+
158+ $ view ->registerJs ($ js );
159+
160+
161+
162+ }
163+
118164}
119165
0 commit comments