依赖下拉 yii2.怎么做? [英] dependent dropdown yii2. How to do?

查看:16
本文介绍了依赖下拉 yii2.怎么做?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 yii2 中创建依赖下拉列表吗?

can I create a dependent dropdown in yii2?

我有两张桌子:

'id','name_country"
'id','name_city','country_id'

并且在我的模型中有两个方法:

and have two methods in my model:

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, 'id', 'name_city','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.

I need to 'transmit' parent_id to controller and return city_list by AJAX (with JSON).

我该怎么做?我看到了 Yii1 中的一个例子,但是 Yii2 呢?

How can I do this? I saw an example in Yii1, but what about Yii2?

推荐答案

使用 krajee 扩展进行依赖下拉

use the krajee extension for dependent drop down

详细信息在这里yii2 的 Krejee 依赖下拉菜单

或遵循以下说明:

通过composer安装扩展:

Install the extension via 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'=>'']);
}

这篇关于依赖下拉 yii2.怎么做?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆