Hi,
I have a "create" form which has 10 fields and it uses CActiveForm. When a field is filled incorrectly and then clicked on create button, the site is refreshed and error message is shown and all previously filled fields are refilled again. However I have two dropdown lists which are dependent on each other via ajax(campus and building, building is dependent on campus) and they are not refilled after refreshing. Below, I put all the codes that may have a role in this problem:
form:
<div class="row">
<?php echo $form->labelEx($model, 'locationId'); ?>
<?php echo $form->dropDownList(Location::model(),'campus', CHtml::listData(Location::model()->findAll(), 'campus', 'campus'),
array(
'empty' =>'--please select--',
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('dynamicBuildings'), //url to call.
'update'=>'#Location_building', //selector to update
)));
?>
<?php echo $form->error(Location::model(),'campus'); ?>
</div>
<div class="row">
<?php echo $form->labelEx(Location::model(), 'building'); ?>
<?php echo $form->dropDownList(Location::model(),'building', array(), array('empty' =>'--please select campus first--')); ?>
<?php echo $form->error(Location::model(),'building'); ?>
</div>
controller- create action
public function actionCreate()
{
$model=new Event;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Event']))
{
$datas = $_POST['Event'];
if(isset($_POST['Location']['building'])){
$locationId = Location::model()->find('campus=:campus AND building=:building',
array(':campus'=> $_POST['Location']['campus'], ':building'=> $_POST['Location']['building']));
$locationId = $locationId['id'];
$datas['locationId'] = $locationId;
}
$datas['userId'] = Yii::app()->user->getID();
$model->attributes=$datas;
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
controller- ajax action:
public function actionDynamicBuildings()
{
//please enter current controller name because yii send multi dim array
//$campus = $_POST['Location'];
$data=Location::model()->findAll('campus=:campus',
array(':campus'=> $_POST['Location']['campus']));
$data=CHtml::listData($data,'building','building');
if($data == null){
echo CHtml::tag('option',
array('empty'),CHtml::encode('--please select campus first--'),true);
}
else{
echo CHtml::tag('option',
array('empty'),CHtml::encode('--please select--'),true);
}
foreach($data as $value=>$building)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($building),true);
}
}
Thanks