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

10 followers

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;
        }
    }
};

Total 5 comments

#18131 report it
nlac at 2014/09/14 01:28pm
@jbowler

check the update, that will solve the problem

#18130 report it
jbowler at 2014/09/14 08:36am
Where does the snippet go?

I'm getting an error:

Uncaught TypeError: Cannot set property 'fix' of undefined

Where does the snippet go?

#14556 report it
bryglen at 2013/08/22 10:29am
does not work

does not work. lack of documentation. add sample source code

#13587 report it
nlac at 2013/06/08 03:12pm
which one among the 3 there and why

The method i published aims to fix CHtml::ajaxSubmitButton to serve better what is it for, enabling real client-side validation. I'm not sure if any of the 3 methods on that link does really make it, however i like one of those too. But hey - anyone can decide what is better for his taste.

#13346 report it
Ben Bi at 2013/05/23 10:13am
i think below link should be better way

http://www.yiiframework.com/forum/index.php/topic/37075-form-validation-with-ajaxsubmitbutton/

Leave a comment

Please to leave your comment.

Write new article