Yii ajaxSubmitButton() with fields validation Yii ajaxSubmitButton() with fields validation ajax ajax

Yii ajaxSubmitButton() with fields validation


Hey I had same problem and dint get it working even with aftervalidate, beforevalidate and so on.And secondly I dint like to use a extension for this coz my app already has many.So I made this:

Edit : As per Barth's suggestion , i am putting those code here itself.

Step 1: @ your controller action

public function actionMyAction()    {                   $model=new User;                         $this->performAjaxValidation($model);              if(isset($_POST['User']))            {                    $model->attributes=$_POST['User'];                    $valid=$model->validate();                                if($valid){                       //do anything here                         echo CJSON::encode(array(                              'status'=>'success'                         ));                        Yii::app()->end();                        }                        else{                            $error = CActiveForm::validate($model);                            if($error!='[]')                                echo $error;                            Yii::app()->end();                        }           }    }

Step 2: @ your view Your form may look like this

<?php$form=$this->beginWidget('CActiveForm', array(    'id'=>'user-form',    'enableAjaxValidation'=>true,    'action'=>$this->createUrl('myController/MyAction'),    'enableClientValidation'=>true, )); ?>    <div class="errorMessage" id="formResult"></div>    <div id="AjaxLoader" style="display: none"><img src="<?php echo Yii::app()->request->baseUrl; ?>/images/spinner.gif"></img></div>    <div class="row-user-single">            <?php echo $form->labelEx($model,'attribute1'); ?>            <?php echo $form->passwordField($model,'attribute1',array('size'=>60,'maxlength'=>500)); ?>            <?php echo $form->error($model,'attribute1'); ?>    </div>    <div class="row-user-single">            <?php echo $form->labelEx($model,'attribute2'); ?>            <?php echo $form->passwordField($model,'attribute2',array('size'=>60,'maxlength'=>500)); ?>            <?php echo $form->error($model,'attribute2'); ?>    </div>    <div class="buttons">     <?php echo CHtml::ajaxSubmitButton('Save',CHtml::normalizeUrl(array('myController/MyAction','render'=>true)),             array(                 'dataType'=>'json',                 'type'=>'post',                 'success'=>'function(data) {                     $("#AjaxLoader").hide();                      if(data.status=="success"){                     $("#formResult").html("form submitted successfully.");                     $("#user-form")[0].reset();                    }                     else{                    $.each(data, function(key, val) {                    $("#user-form #"+key+"_em_").text(val);                                                                        $("#user-form #"+key+"_em_").show();                    });                    }                       }',                                     'beforeSend'=>'function(){                                               $("#AjaxLoader").show();                  }'                 ),array('id'=>'mybtn','class'=>'class1 class2')); ?>

This is working just fine for me And all the code written above are my style of writing. You may change them as required but,there are only two things to be noted as follows:1. @ your controller call validate of your model and return a json object if form is invalid2. @ your view break this json object (OR traverse through it) and show the error messages under respective elements of the form.

Keep it simple :)

You may see my blog post here too:http://www.yiiframework.com/forum/index.php/topic/37075-form-validation-with-ajaxsubmitbutton/


CActiveForm has a public property called $clientOptions. There is a validateOnSubmit option that is false by default. You need it to be true. In your view it should look something like this:

<?php $form=$this->beginWidget('CActiveForm', array(    'id'=>'yourFormId',    'enableAjaxValidation'=>TRUE,    'clientOptions'=>array('validateOnSubmit'=>TRUE),)); ?>

http://www.yiiframework.com/doc/api/1.1/CActiveForm#clientOptions-detail


I found a solution.My CActive Form

<?php $form=$this->beginWidget('CActiveForm', array(    'id'=>'gold-value-form',    'enableAjaxValidation'=>true,    'clientOptions'=>array(        'validateOnSubmit'=>true,        'afterValidate'=>'js:function(form, data, hasError) {            if(jQuery.isEmptyObject(data)) {                alert("ok")            }            return false;        }'    ),)); ?>

My create Action

public function actionCreate(){    $this->layout=false;    $model=new GoldValue;    if(isset($_POST['ajax']) && $_POST['ajax']==='gold-value-form')    {        if(isset($_POST['GoldValue']))        {            $model->attributes=$_POST['GoldValue'];            if(!$model->save())                echo CActiveForm::validate($model);        }    }    Yii::app()->end();}