我按照Youtube教程创建了一个依赖的DropdownList(州和城市),加载后不久,Dropdownlist City显示所有城市。
我希望在选择州时不会显示任何内容。但我不知道该怎么做,想要一些帮助。
看看我是怎么做的:
查看:_search.php
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model,'state_id')->dropDownList(
ArrayHelper::map(State::find()->all(), 'id', 'nome'),
[
'prompt'=>'Selecione',
'onchange'=>'
$.get( "'.Url::toRoute('/city/lists').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'city_id').'" ).html( data );
}
);'
]);
?>
<?= $form->field($model,'city_id')->dropDownList(
ArrayHelper::map(City::find()->all(), 'id', 'name'),
[
'prompt'=>'Selecione o estado',
]);
?>
CONTROLLER:CityController.php
public function actionLists($id)
{
$countCity = City::find()
->where(['state_id' => $id])
->count();
$cities = City::find()
->where(['state_id' => $id])
->all();
if($countCity > 0 )
{
foreach($cities as $city ){
echo "<option value='".$city->id."'>".$city->name."</option>";
}
}
else{
echo "<option> - </option>";
}
}
SQL:
CREATE TABLE `city` (
`id` int(11) NOT NULL,
`name` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,
`state_id` int(11) DEFAULT NULL,
`population_2010` int(11) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
-- --------------------------------------------------------
CREATE TABLE `state` (
`id` int(11) NOT NULL,
`name` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL,
`sigla` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
答案 0 :(得分:1)
在onchange()
中添加此代码 $.get( "'.Url::toRoute('/city/lists').'", { id: $(this).val() } )
.done(function( data ) {
$( "select#selectid" ).html( data );
}
);'
<select id="selectid"></select>
您必须从
返回选项值actionList($id){
$list=Model::findBySql('your quer where id=$id')->all()
foreach($list as $l){ echo "<option value='" $l->id."'>'.$l->name.'</option>';
}
我建议你观看这个视频