我可以在yii2中创建依赖下拉列表吗?
我有两张桌子:
'id','name_country" 'id','name_city','country_id'
我的模型中有两种方法:
public function getCountryList() { $models = NetCountry::find()->asArray()->all(); return ArrayHelper::map($models,'id','country_name'); }
和
public function getCityList($parent_id) { $models = \common\models\City::find()->where(['parent_id' => $country_id])->asArray()->all(); return ArrayHelper::map($models,'country_id'); }
我有第一个字段:
<?= $form->field($model,'country')->dropDownList($model->countryList),['id'=>'parent_id'];
第二个
<?= $form->field($model,'city')->dropDownList($model->cityList);
我需要’传递’parent_id到控制器并通过AJAX(使用JSON)返回city_list.
我怎样才能做到这一点?我看到an example in Yii1,但是Yii2怎么样?
使用krajee扩展来依赖下拉
细节在这里Krejee dependent dropdown for yii2
或按照以下说明操作:
通过composer安装扩展:
$PHP composer.phar require kartik-v/dependent-dropdown "dev-master"
在你看来:
use kartik\widgets\DepDrop; // Normal parent select echo $form->field($model,'cat')->dropDownList($catList,['id' => 'cat-id']); // Dependent Dropdown echo $form->field($model,'subcat')->widget(DepDrop::classname(),[ 'options' => ['id' => 'subcat-id'],'pluginOptions' => [ 'depends' => ['cat-id'],'placeholder' => 'Select...','url' => Url::to(['/site/subcat']) ] ]);
//控制器
public function actionSubcat() { $out = []; if (isset($_POST['depdrop_parents'])) { $parents = $_POST['depdrop_parents']; if ($parents != null) { $cat_id = $parents[0]; $out = self::getSubCatList($cat_id); // the getSubCatList function will query the database based on the // cat_id and return an array like below: // [ // ['id'=>'<sub-cat-id-1>','name'=>'<sub-cat-name1>'],// ['id'=>'<sub-cat_id_2>','name'=>'<sub-cat-name2>'] // ] echo Json::encode(['output'=>$out,'selected'=>'']); return; } } echo Json::encode(['output'=>'','selected'=>'']); }