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

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;
		}
	}
};
4 1
11 followers
Viewed: 63 871 times
Version: 1.1
Category: Tutorials
Written by: nlac
Last updated by: nlac
Created on: Mar 17, 2013
Last updated: 10 years ago
Update Article

Revisions

View all history

Related Articles