A simple way to get Yii client-side form validation run when submitting by ajax

4 1
11
Viewed: 69 415 times
Version: Unknown (update)
Category: Tutorials
Written by: nlac nlac
Updated by: nlac nlac
Created: Mar 17, 2013
Updated: 11 years ago

You are viewing revision #2 of this wiki article.
This is the latest version of this article.
You may want to see the changes made in this revision.

« previous (#1)

A time ago i've met the issue that Yii doesn't run any client-side form validation when submitting the form by CHtml::ajaxSubmitButton. The small javascript below helps to fix it.

Update!

Replaced the $.yii.fix expression everywhere to yiiFix in the tutorial, so the dependency from jquery.yii.js has been removed.

Usage

1) Register the snippet into the HEAD.

2) Configure your CActiveForm instance like this:

$this->beginWidget('CActiveForm', array(
	...
	'enableClientValidation'=>true,
	'clientOptions'=>array(
		'validateOnSubmit'=>true,
		'afterValidate'=>'js:yiiFix.ajaxSubmit.afterValidate'
	)
	...
);

3) Configure your CHtml::ajaxSubmitButton instance like this:

echo CHtml::ajaxSubmitButton('Whateverlabel', 'whateverurl', array(
	...
	'beforeSend'=>'js:yiiFix.ajaxSubmit.beforeSend("#YOUR_FORM_ID")'
	...
);

The snippet
;yiiFix = {
	ajaxSubmit : {	
		beforeSend : function(form) {
			return function(xhr,opt) {
				form = $(form);
				$._data(form[0], "events").submit[0].handler();
				var he = form.data('hasError');
				form.removeData('hasError');
				return he===false;
			}
		},
		
		afterValidate : function(form, data, hasError) {
			$(form).data('hasError', hasError);
			return true;
		}
	}
};