how to make AjaxValidation like ClientValidation?

i have a problem…

i want to make a AjaxValidation with my form…

i use onChange to make error warning like ClientValidation…

i want this error like this.

2654

My Web Application - Cp-144215.png

but now, my error like this…

2655

My Web Application - Operator-144325.png

how to create error message like 2654

My Web Application - Cp-144215.png
with AjaxValidation???

this is my code.

_form.php




<div class="row">

		<?php echo $form->labelEx($model,'code'); ?>

		<?php echo $form->textField($model,'code',array('id'=>'code',

                'ajax'=>array(

                    'type'=>'POST',

                    'url'=>Yii::app()->createUrl('operator/validcode'),

                    'update'=>'#error_message'

                )

               )); ?>

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

	</div>

    <div id="error_message" style="color:red; font-size:12px">

    		

    </div>

operatorController.php




public function actionValidcode()

	{

		$code = $_POST['Operator']['code'];

		$code1 = Operator::model()->findAll('code=:vcode', array(

			':vcode'=>$code, 

		));

		foreach($code1 as $a)

		{

			echo $code.' sudah terdapat dalam database..!';

		}		

	}



Why don’t leave the form as it was, enable Client+Ajax validation, and move your action to a function in the model, and add that function in the model rules for that field?

Like that:

in the _form.php view:


$form=$this->beginWidget('CActiveForm', array(

	'id'=>'operator-form',

	'enableClientValidation'=>true,

	'enableAjaxValidation'=>true,

	(…)

	<div class="row">

		<?php echo $form->labelEx($model,'code'); ?>

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

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

	</div>

in the Operator model, taking your validation code:


class Operator extends CActiveRecord

{

	(…)

	public function rules()

	{

		return array(

			(…)

			array('code', 'validateCode'),

			(…)

	}

	(…)

	public function validateCode($attribute, $params) {

		if(isset($_POST['Operator']['code'])) {

			$code = $_POST['Operator']['code'];

			$code1 = Operator::model()->findAll('code=:vcode', array(

				':vcode'=>$code, 

			));

			foreach($code1 as $a)

				$this->addError($attribute, $code.' sudah terdapat dalam database..!');

		}

		return false;

	}

	(…)

}

On a side note, I don’t understand your error message, but it seems like you want $code to be unique? If that’s the case, you could directly specify it in the rules with your custom message.


array('code', 'unique', 'message'=>' sudah terdapat dalam database..!');

I don’t know whether it’s possible to display the value of code attribute in the error message.