Hi folks, I’m trying to set up a dependent dropdown list, in which a department is selected from the first dropdown list, and then the second dropdown list is populated with the courses belonging to that department. I’ve almost got it working, but my $POST array is not receiving the data from the view. Here is my code:
In the view courseTaken/_form.php:
<div class="row">
<?php
echo $form->labelEx($model,'department_id');
echo CHtml::dropDownList('department_id','', CHtml::listData(Department::model()->findAll(array(
'order'=>'department_name ASC')), 'id', 'department_name'),
array('ajax'=>array(
'type='=>'POST',
'url'=>CController::createUrl('course/CoursesByDept'),
'update'=>'#course_id',
'data'=>array('department_id'=>'js:this.value'),
)));
echo $form->error($model,'department_id');
?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'course_id'); ?>
<?php echo CHtml::dropDownList('course_id', '', array()); ?>
<?php echo $form->error($model,'course_id'); ?>
</div>
In the controller CourseController:
public function actionCoursesByDept()
{
$data=Course::model()->findAll('department_id=:department_id',
array(':department_id'=>(int) $_POST['department_id']));
//array(':department_id'=>1));
$data=CHtml::listData($data,'id','course_number');
foreach($data as $value=>$name) {
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($name),true);
}
}
Using Firefox and Firebug, I see the error: Undefined index: department_id
on the line with the $POST array. If I comment out the line with the $POST array, and just manually assign an id:
$data=Course::model()->findAll('department_id=:department_id', array(':department_id'=>1));
the course dropdown in the view gets loaded with all of the courses with department_id = 1.
Does anyone know why the $POST array is empty?
The CourseTaken model does not have the field department_id, the Course model does, so I’ve put:
public $department_id;
inside the CourseTaken model, but I get the same error.
I’ve read the wiki articles http://www.yiiframework.com/wiki/24/ and http://www.yiiframework.com/wiki/429/an-easy-solution-for-dependent-dropdownlist-using-ajax/
and read lots of forum posts, but the problem still eludes me.
Any help appreciated.
Stumped,
Larry