问题
I have a dropdown that I want to populate when an item in another dropdown is selected. Both the dropdown are tied to data/model passed on from controller. and the first dropdown is populated from DB by calling a function in the model. Heres' the form,
echo $form->dropDownListRow($modelunit,
'superunit',
$model->getSunits(),
array(
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('user/getunits'),
'update'=>'#unit_id',
)));
echo CHtml::dropDownList('unit_id','', array());
Here's the action user/getunits called by Ajax.
$data=Unit::model()->findAll('sid=:sid',
array(':sid'=>(int) $_POST['superunit']));
$data=CHtml::listData($data,'id','name');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
I keep getting an error "Undefined index: superunit" when first dropdown is selected. Also, you may notice I am using form->dropDownListRow for the first dropdown while using CHtml::dropDownList for the second. That's cause I am clueless on the syntax of how exactly to make sure the dropdown is populated correctly with ajax and at also properly bind to the model.
回答1:
You use $form->dropDownListRow
that's why you will get $_POST['MyModelName']['superunit']
on your server side
Change you code like
$data=Unit::model()->findAll('sid=:sid',
array(':sid'=>(int) $_POST['MyModelName']['superunit']));
Where MyModelName
is a model that you use)
Or like
echo CHtml::dropDownList('superunit'.....
For others - this wiki may help.
来源:https://stackoverflow.com/questions/18937382/yii-populate-a-dropdown-on-select-of-another