Load Data By Ajax Disappeared When Valdiation Return Erorr

Hi

I had form content first name , last name …etc . And tow drowpdownlist countries and cites , I loaded cites when Country drowpdownlist changed by ajax , and everything is cool . My problems :

1- when clicked submit and had error in validation , city value will replaced with empty value How To fix it ?

2- How to use $form-> with it I mean city drowpdownlist .

  • Form work if no error in validation
  • Form after clicked on submit and return error in validation like username is empty …etc

View :





		<div class="row">

		<?php echo $form->labelEx($model,'البلد'); ?>

	<?php

	

	/*

 	echo chtml::activeDropDownList($model,'country',$model->getcountry(),array('prompt'=>'اختر بلدك ')   , 

	array(

'ajax' => array(

'type'=>'POST', //request type

'url'=>CController::createUrl('current/dynamiccities'), //url to call.

//Style: CController::createUrl('currentController/methodToCall')

'update'=>'#city', //selector to update

//'data'=>'js:javascript statement' 

//leave out the data key to pass all form values through

))

	

	); 

	

	*/

	echo CHtml::activedropDownList($model,'country',$model->getcountry(),

	

	array(

	'prompt'=>'اختر البلد أو المنطقة ',

'ajax' => array(

'type'=>'POST', //request type

'url'=>CController::createUrl('register/dynamiccities'), //url to call.

//Style: CController::createUrl('currentController/methodToCall')

'update'=>'#city', //selector to update

//'data'=>'js:javascript statement' 

//leave out the data key to pass all form values through

))

	);

   

   

   ///

   

   


	

	////

	

	?>

 

	

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

	</div>

	<div class="row">

		<?php echo $form->labelEx($model,'المدينة'); ?>

		<?php 


echo CHtml::dropDownList('city','', array());








 ?>

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

	</div>



Ajax Controller


public function actionDynamiccities() /// Called Ajax

{




$country=intval($_POST['Users']['country']);




   	$data=Cities::model()->findAll('country_id=:country_id', 

              	array(':country_id'=>$country));

	$data=CHtml::listData($data,'id','city_name_e');

 	echo CHtml::tag('option',

            	array('value'=>''),CHtml::encode('Select Your City '),true);


	foreach($data as $value=>$name)

	{

    	echo CHtml::tag('option',

               	array('value'=>$value),CHtml::encode($name),true);

	};




}




Thanks in advance

Up :(

you should be able set a value for your city column in your create action I can point you in the direction only if you could upload all your controller code

Thank you alirz , My full controller :





  

	public function actionIndex()

{

	$model=new Users('register');


	// uncomment the following code to enable ajax-based validation

	/*

	if(isset($_POST['ajax']) && $_POST['ajax']==='users-index-form')

	{

    	echo CActiveForm::validate($model);

    	Yii::app()->end();

	}

	*/







	if(isset($_POST['Users']))

	{

    	$model->attributes=$_POST['Users'];

    	




  

    	if($model->validate())

    	{

    	

    	/// get data 

       	$password=sha1($_POST['Users']['password']);

       	$email=$_POST['Users']['email'];

       	$first_name=$_POST['Users']['first_name'];

       	$last_name=$_POST['Users']['last_name'];

       	$active_key=substr($password,1,7).rand(1,587875483);

       	$mobile_code=$_POST['Users']['mobile_code'];

       	$mobile_number=$_POST['Users']['mobile_number'];

       	$country=$_POST['Users']['country'];

       	$city=$_POST['Users']['city'];

       	$gender=$_POST['Users']['gender'];

       	$birth_date=$_POST['Users']['birth_date'];

       	

       	

       	/// insert into datbase 

       	

        	$sql =Yii::app()->db->createCommand(" INSERT INTO `tbl_users` (`user_id`, `first_name`, `last_name`, `password`, `active_key`, `Email`,`city`,`country`,`birth_date`,`gender`,`reg_date`) 	

                    	values(NULL,'$first_name','$last_name','$password','$active_key','$email','$city','$country','$birth_date','$gender',NOW()) ")->query();

       	

    	

        	/////// send active email 

	

	

	if($sql){  

    	


    	

        	function send_mail($to,$from,$subject,$msg){

		// message

		$message = '

		<html>

		<head>

		  <title>Activation </title>

		</head>

		<body dir="rtl">

		<p align="right">'

    	. $msg .

		'</p>

		<br>


		</p>

		</body>

		</html>

		';


		// To send HTML mail, the Content-type header must be set

		$headers  = 'MIME-Version: 1.0' . "\n";

		$headers .= 'Content-type: text/html; charset=windows-1256' . "\n";


		// Additional heade rs

		$headers .= "From: ".$from . "\n";

	  


		// Mail it

		return mail($to, '=?windows-1256?B?'.base64_encode($subject).'?=', $message, $headers);

	}

	


$subject=" بقي لديك خطوة واحدة لإكمال تسجيلك ";


$url=Yii::app()->request->serverName;

$message=' 


$url/ict/index.php/register/Active/key/$active_key




<a href=\"$url/ict/index.php/register/Active/key/$active_key\">Click Here Please </a>


<style type="text/css">

<!--


body{

  	background-color:#F7F7F7; 

}


.pagelayout{

   

   alignment-adjust: central;


   width: 1000px;

 

}


.title{

  font-size: 16px;

  font-family: "lucida grande",tahoma,verdana,arial,sans-serif;

  background: #3b5998;

  color: #ffffff;

  font-weight: bold;

  vertical-align: baseline;

  letter-spacing: -0.03em;

  text-align: left;

  padding: 10px 10px 4px;


}




.content{

	

  

  font-size: 11px;

  font-family: LucidaGrande,tahoma,verdana,arial,sans-serif;

  padding: 10px 20px;

  background-color: #ffffff;

  border-left: #cccccc;

  border-right: #cccccc;

  border-width: 1px;

  border-style: solid;

  border-color: #cccccc;

  line-height: 16px;

  width: 600px;




}


.buttonbar{

  font-size: 11px;

  font-family: LucidaGrande,tahoma,verdana,arial,sans-serif;

  padding: 10px;

  background-color: #f2f2f2;

  border-left: medium none;

  border-right: medium none;

  border-width: 1px medium;

  border-style: solid none;

  border-color: #cccccc;


}


.website{

	

	font-size: 13px;

 padding-top: 5px;

 padding-right:2px ;




}

.websitebutton{


  border-width: 1px;

  border-style: solid;

  border-color: #29447e;

  background-color: #5b74a8;

  border-left: #cccccc;

  border-right: #cccccc;

  border-width: 1px;

  border-style: solid;

  border-color: #cccccc;

  line-height: 16px;

  width: 100px;

  height: 30px;


	

}


.graybuttontext{

  font-weight: bold;

  white-space: nowrap;

  color: #333333;

  font-size: 13px;


}


.graybutton{

  font-size: 11px;

  font-family: LucidaGrande,tahoma,verdana,arial,sans-serif;

  padding: 2px 6px 4px;

  border-top: #ffffff;

  border-left: #cccccc;

  border-right: #cccccc;

  border-width: 1px;

  border-style: solid;

  border-color: #cccccc;

  line-height: 16px;

}


.footer{

  font-size: 11px;

  font-family: "lucida grande",tahoma,verdana,arial,sans-serif;

  padding: 10px;

  background-color: #ffffff;

  color: #999999;

  border: medium none;

text-align: right;

}


.webcontent{

 float: right;   

	

}

	

.hrcolor{


  border-width: 1px;

  border-style: solid;

  border-color: #cccccc;

  line-height: 16px;

}


.messagetext{

	

   

  font-size: 13px;

  font-family: LucidaGrande,tahoma,verdana,arial,sans-serif;




}


a{

  	font-weight: bold;

  white-space: nowrap;

  color: #ffffff;

  font-size: 13px;

 padding-top: 5px;

 padding-right:2px ;

  text-decoration:none;

	

}

-->

</style>

<body>


<div class="pagelayout">

<div class="webcontent">

<table dir="rtl">

<tr>

	<td class="title"> <img src="*" width="200" height="44" /></td>

</tr>

<tr>

	<td class="content">

 <div class="messagetext">

 <br /> 

 

   <br />

 مرحبا : '.$first_name.'

	شكرا لأختيارك التسجيل معنا , بقي عليك خطوة واحدة فقط لإتمام عملية التسجيل 

 <br />

 وهي تفعيل حسابك من خلال الضغط على زرّ تفعيل حساب

   

	</div>

  <br />

	<div class="buttonbar"> 

	

 <div class="websitebutton">   <div class="website"> <a href="#">تفعيل الحساب</a></div> </div>

 

 <!-- 

 <div class="graybutton"><div class="graybuttontext">إرشادات ومعلومات</div> </div>

 	-->

	</div>

   	<hr class="hrcolor" />

   	في حال لم يكن الرابط مفعّل قم بنسخ الرابط اعلاه <br/>

 (تأكد من نسخ كامل الرابط ) وألصقه في شريط العنوان في  برنامج متصفح الانترنت لديك واضغط على (أذهب - Go)

</tr>

<tr>

	<td></td>

</tr>

</table>

<div class="footer">


</div>

</div>

</div>





';


 send_mail($email,'noreply@***.net',$subject,$message);


}

	//// End mail Function 




        	//// Start Flash message 

        	

        	Yii::app()->user->setFlash('success','رسالة إدارية<br/>

             	

    	شكرا لك , تمت عمليّة التسجيل بنجاح <br />

    	تمّ إرسال رابط تفعيل الحساب إلى بريدك الإلكتروني 

             	

             	

              	');


        	

        	

       	/////// End Active 

        	

        	

       	

    	$this->redirect(array('site/login'));	

        	

        	

        	

        	

        	

      	

    	}

    	else{

         	Yii::app()->user->setFlash('error','رسالة إدارية 

         	<br />

         	هنالك مشكلة في عملية التسجيل يرجى مكالمة الدعم التقني 

         	

         	

       	

         	

         	');


        	

       	// $this->redirect(array('site/'));   

    	}

	}

 $this->render('index',array('model'=>$model));

}






Also I Wrote my question in stackovelflow but answer not work :(

Thanks in advance

all your controller code is right this where is your problem is

<div class="row">

<?php echo $form->labelEx($model,‘المدينة’); ?>

<?php echo CHtml::dropDownList(‘city’,’’, array()); ?> // right here

<?php echo $form->error($model,‘city’); ?>

</div>

take look at the guide comment section

http://www.yiiframework.com/wiki/24/creating-a-dependent-dropdown/

I copied it from stackoverflow

It seems to me like what you need to do is look at the $_POST variables to see which dependent dropdown was selected, and pre-render it when the form validation fails so Yii’s default validation errors work. Using this link as an example:

First, refactor out part of the actionDynamiccities() method into a separate public (non-action) method in your controller:




public function getCitiesList($country_id) {

    $data=Location::model()->findAll('parent_id=:parent_id', 

              array(':parent_id'=>(int) $country_id));

    return CHtml::listData($data,'id','name');

}

Then fix your refactored AJAX action like so:




public function actionDynamiccities()

{

  $data = $this->getCitiesList($_POST['country_id']);

  foreach($data as $value=>$name)

  {

    echo CHtml::tag('option',

               array('value'=>$value),CHtml::encode($name),true);

  }

}



Then in your _form.php view file, in the #city_id div where the second dropdown would be AJAXed in by the first, add a little PHP snippet like this:


<div id="city_id">

<?php if(isset($_POST['city_id'])): ?>

  <?php foreach($this->getCitiesList($_POST['country_id']) as $value=>$name): ?>

    <?php echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true); ?>

  <?php endforeach; ?>

<?php endif; ?>

</div>



This way, if you have already submitted the form and the $_POST[‘country_id’] is set, the dependent dropdown is already rendered and it should display the appropriate validation errors.

If the user selects a different country the city dropdown should be replaced like normal still.

I didn’t test this code but it should work in principle. Good luck!

Ali I built my drwoownlist related to this article , I Checked it before I did anything :)

<?php echo CHtml::dropDownList(‘city’,’’, array()); ?> // right here

yes this my problem , My problem is how to related this field to form $model like in country dropdwonlist


chtml::activeDropDownList($model,'country',$model->getcountry(),array('prompt'=>'اختر بلدك ') 

How To do that with dropDownList ???!!! in city field

Thanks in advance

I have update the last comment please do take look at it, straight forward it you still dont get it i will help you rewrite it

Ali , I tested your idea and it’s worked but I had some problem

This my new code :

Controller





public function getCitiesList($country) {

	$data=Cities::model()->findAll('country_id=:country_id', 

          	array(':country_id'=>(int)$country));

	return CHtml::listData($data,'id','city_name_e');

}


public function actionDynamiccities()

{

  $country=intval($_POST['Users']['country']);

  $data = $this->getCitiesList($country);

  foreach($data as $value=>$name)

  {

	echo CHtml::tag('option',

       		array('value'=>$value),CHtml::encode($name),true);

  }

}







View :




<div class="row">




<?php if(isset($_POST['city'])): ?>


  <?php

  

  $data=array();

   foreach($this->getCitiesList($_POST['Users']['country']) as $value=>$name): ?>

	<?php $data[]= CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true); ?>


  <?php endforeach; ?>

  <?php

echo chtml::activeDropDownList($model,'city',$data,array('prompt'=>'Select Your City')

);

?>

<?php endif; ?>

<?php if(!isset($_POST['city'])):?> 

<?php 

 echo CHtml::dropDownList('city','', array());

?>


<?php endif; ?>

</div>




problem image after forum submitted :

Thanks Ali For everything

Thanks Ali I fixed it :) B)