blog-banner

Yii - How To Enable Ajax Form Validation

  • Ajax
  • form
  • YII

Form validation ensures that each and every field in the form has been filled in the required way. No further prelude is required to this topic as Developers would be well aware of the purpose and function of form validations. In one of my bygone projects, I had a claim to validate a form with AJAX which I did successfully.

I found fewer online references while trying to achieve the purpose, hence thought of leaving a path to others so that this can be used as a reference, The following steps should be used to validate your Yii form using AJAX.

STEP 1:  Declaring beginWidget()

In your Yii view form, declare beginWidget as mentioned below,

  1. <?php
  2.   $form = $this->beginWidget('CActiveForm', array(
  3.     'id'=>'form',  //form-id
  4.     'enableAjaxValidation'=>true,
  5.     'clientOptions'=>array(
  6.       'validateOnSubmit'=>true,
  7.      ),
  8.  ));
  9. ?>
 
And have form elements with a matching error function. 
 
  1. <div class="row">
  2.  <?php echo $form->labelEx($model,'attribute'); ?>
  3.  <?php echo $form->textField($model,'attribute'); ?>
  4.  <?php echo $form->error($model, 'attribute'); ?>
  5. </div>
  6.  
  7. <div class="row">
  8.  <?php echo $form->labelEx($model,'attribute1'); ?>
  9.  <?php echo $form->textField($model,'attribute1'); ?>
  10.  <?php echo $form->error($model, 'attribute1'); ?>
  11. </div>
 
Once the matching error functions have been written the Widget function can be closed with the below-mentioned syntax.
 
  1. <?php
  2.   $this->endWidget();
  3. ?>
 
The above-mentioned step will include jquery.yiiactiveform.js, thus it is mandatory to have STEP 1. 
 
STEP 2: Generating Response
 
In the controller, We need a response to the Ajax validation request. To do so make use of the below code
 
  1. if(isset($_POST['ajax'])) {
  2.   if ($_POST['ajax']=='form') {
  3.     echo CActiveForm::validate($model);
  4.   }
  5.   Yii::app()->end();
  6. }
 
STEP 3: Validation Rule
 
Make sure your model has at least one validation rule for that scenario
   
  1. public function rules()
  2. {
  3.   return array(
  4.     array('attribute, attribute1', 'required'),
  5.   );
  6. }
  
STEP 4: Div Element
 
When we use $form->error(), Yii includes a hidden div after your form element.
  
  1. <input id="attribute" type="text" name="[attribute]" maxlength="120" size="20">
  2. <div id="attribute_em_" class="errorMessage" style="display:none"></div>
  
STEP 5: Change Div Style
 
If a field has a validation error, Yii changes the div style from none to block and adds an error message to that field. Hence whenever a field has failed in form validation the response can be seen in AJAX.
 
Hope this concept helps Yii developers.
Get awesome tech content in your inbox