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

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

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.

Usage ¶

1) Register the snippet into the HEAD. Be sure that it is linked after jquery.yii.js is linked.

2) Configure your CActiveForm instance like this:

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

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

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

The snippet ¶
;$.yii.fix = {
	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: 67 489 times
Version: Unknown (update)
Category: Tutorials
Written by: nlac nlac
Last updated by: nlac nlac
Created on: Mar 17, 2013
Last updated: 11 years ago
Update Article

Revisions

View all history

Related Articles