July 23, 2014

July 23, 2014
In this article, we are going to discuss about How to implement the Ajax form validation in YII PHP Framework. Yii supports AJAX form validation, which essentially posts the form values to the server, validates them, and sends back the validation errors, all without leaving the page. It does this every time you tab out of a (changed) field.

Here's how Yii's AJAX validation works:

Step 1 : 

Add the below code in your yii form declaration

<php $form = $this->beginWidget('CActiveForm', array(
'id'=>'lowercasemodelname-form', //not technically required but works w gii generated controllers
'enableAjaxValidation'=>true //turn on ajax validation on the client side
));

And have at least one form element with a matching error function:

<?php echo $form->textField($model, 'my_attribute'); ?>
<?php echo $form->error($model, 'my_attribute'); ?>

This makes Yii include the JQuery javascript library, as well as a Yii javascript file called jquery.yiiactiveform.js

Step 2:

In your controller file, in create or update, after you load the model, but before you load it from POST, call this

if(Yii::app()->getRequest()->getIsAjaxRequest()) {
echo CActiveForm::validate( array( $model)); 
Yii::app()->end(); 
}

Which is sligtly different than how Gii generates it, but no big diff. CActiveForm::validate() can take an array of models, which is not clear the way Gii does it.

Step 3: 

Make sure that your model has at least one validation rule for the insert or update scenario. After you tab out of a changed field, Yii sends a standard AJAX POST to the server, and gets back a JSON response like this:

{"Field_id":["Validation error a"],"Another_field_id":["Validation error B"]}

which yii then plugs into the error field below your field.

Step 4:

When you use the $form->error() function, Yii adds a hidden div after your form element:

<div id="Model_attributename_em_" class="errorMessage" style="display:none"></div>

If that field has a validation error, then Yii sets the display to block, writes the validation error message to its innerHtml, and then you see the error. If it later validates, yii hides it again.

Step 5: 

Yii will also add class names to the parent container of the field that it's validating. In most cases, this is a <div class="row">. When a form field is valid, it adds "success" class to the div - which makes it green. When it's invalid, it adds "error" class, which makes it red. It also quickly adds a "validating" class, which does nothing, but you can supply it yourself and change the look of a field while it's validating.

0 comments:

Post a Comment