Guys need help with this…I am trying to follow the wiki http://www.yiichina.net/forum/index.php/topic/20738-solveddependent-dropdown-list/ .
I have 3 tables. 1. Ticket 2. Vehicle Type 3. Offence
Vehicle Type table has a name and Type field that takes either 1 or 2. 1 means 4-wheel drive and 2 means 2-wheel drive. Second Table offence lists down different types of violations along with TypeID. For example "Not wearing a helmet" would have a typeID 2 (2-wheel drive).
CREATE TABLE Vehicle (
id int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL,
`type` tinyint(4) DEFAULT NULL,
PRIMARY KEY (id),
KEY `type` (`type`)
)
CREATE TABLE Offence (
id int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(256) NOT NULL,
typeId tinyint(4) NOT NULL,
PRIMARY KEY (id),
KEY id (id),
KEY typeId (typeId)
)
Offence.php Model file
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'tickets' => array(self::HAS_MANY, 'Ticket', 'offenceId'),
'vehicles' => array(self::HAS_MANY, 'Vehicle', 'type'),
);
}
Vechicle.php Model file
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'type0' => array(self::BELONGS_TO, 'Offence', 'type'),
);
}
Now, in my view file I populate the vehicleID however, once the selection is made I want populate the OffenceID field based on the Type given in VehicleID. View file
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'ticket-form',
'enableAjaxValidation'=>true,
)); ?>
<div class="row">
<?php echo $form->labelEx($model,'vehicleId'); ?>
<?php echo $form->dropDownList($model,'vehicleId',CHtml::listData(Vehicle::model()->findAll(), 'id', 'name'), array('ajax' => array('type'=>'POST','url'=>CController::createUrl('currentController/dynamicoffence'), 'update'=>'#offenceId',) ); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'offenceId'); ?>
<?php echo $form->dropDownList($model,'offenceId',array()); ?>
</div>
So basically I need to make a call to a function in the controller. The controller will read the currently selected value in the VehicleID dropdown. Check the Vehicle ID table for "type". Then for this type retrieve values (id and name) from the offence table. So how do I do this please help. This is my controller.
public function actionDynamicoffence()
{
$data=Vehicle::model()->findByPk($_POST['vehicleId']);
$temp=$data->type;
$data=Offence::model()->findAll('parent_id=:parent_id',
array(':parent_id'=>(int) $temp);
$data=CHtml::listData($data,'id','name');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}