Monday, July 03, 2017

Yii Form Validation With Ajax submit button

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')); ?>
<?php $this->endWidget();?>
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 invalid
2. @ your view break this json object (OR traverse through it) and show the error messages under respective elements of the form.

For more refer please go to the link . Thanks to  riyazMuhammed