Skip to content

Commit 00a41eb

Browse files
committed
Added ActiveForm ajax submit support
Added ActiveForm ajax submit support. Now you can use the param useWithActiveForm to specify the name of the ActiveForm. Client validation and ajax submit is working!
1 parent 68cfa2d commit 00a41eb

File tree

1 file changed

+48
-2
lines changed

1 file changed

+48
-2
lines changed

AjaxSubmitButton.php

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)