Hi,
I started training myself Yii framework three weeks ago.
I kindly need help on dependent drop down list.I have read many wikis but my problem still persists.
I have three tables namely;
Businessdetails
pinnumber PK
countyid
constituencyid
ward
Counties
countyid PK
countyname
Constituencies
countyid
constituencyid PK
constiyuencyname
I have a form that allows one to register business information to businessdetails table. The form is already loading counties from the table ‘counties’ as a dropdown. I want when one selects a county, constituencies under that county are loaded in the constituency as a dropdown.
My view and controller code are below but not working.
[size="5"]VIEW[/size]
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'businessdetails-form',
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation'=>true,
'clientOptions'=>array('validateOnSubmit'=>true),
)); ?>
<div class="row">
<?php echo $form->labelEx($model,'countyid'); ?>
<?php
echo $form->dropDownList($model,'countyid',CHtml::listData(Counties::model()->findAll(), 'countyid', 'countyname'),
array(
'prompt'=>'-Select County-',
'ajax' => array
(
'type'=>'POST',
'url'=>CController::createUrl('Businessdetails/loadconstituencies'), //or $this->createUrl('loadcities') if '$this' extends CController
'update'=>'#constituencyid', //or 'success' => 'function(data){...handle the data in the way you want...}',
'data'=>array('countyid'=>'js:this.value'),
)));
?>
<?php echo $form->error($model,'countyid'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'constituencyid'); ?>
<?php echo $form->dropDownList($model,'constituencyid',array()); ?>
<?php echo $form->error($model,'constituencyid'); ?>
</div>
[size="5"]CONTROLLER[/size]
public function actionLoadconstituencies()
{
$data= Constituencies::model()->findAll('countyid=:countyid',array(':countyid'=>(int) $_POST['countyid']));
$data=CHtml::listData($data,'constituencyid','constituencyname');
foreach($data as $value=>$constituency)
{
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($constituency),true);
}
}
Kindly help