依赖下拉yii2.怎么做?

Sli*_*lip 2 yii2

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

我有两张桌子:

'id','name_country"
'id','name_city','country_id'
Run Code Online (Sandbox Code Playgroud)

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

public function getCountryList()
{
$models = NetCountry::find()->asArray()->all();
return ArrayHelper::map($models, 'id', 'country_name');
} 
Run Code Online (Sandbox Code Playgroud)

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');
}
Run Code Online (Sandbox Code Playgroud)

我有第一个字段:

 <?= $form->field($model, 'country')->dropDownList($model->countryList),['id'=>'parent_id'];
Run Code Online (Sandbox Code Playgroud)

第二个

<?= $form->field($model, 'city')->dropDownList($model->cityList);
Run Code Online (Sandbox Code Playgroud)

我需要'传输' parent_id到控制器并city_list通过AJAX 返回(使用JSON).

我怎样才能做到这一点?我在Yii1中看到了一个例子,但是Yii2怎么样?

小智 6

使用krajee扩展来依赖下拉

详细信息在这里是针对yii2的Krejee依赖下拉列表

或按照以下说明操作:

通过composer安装扩展:

 $ php composer.phar require kartik-v/dependent-dropdown "dev-master"
Run Code Online (Sandbox Code Playgroud)

在你看来:

  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'])
    ]
]);
Run Code Online (Sandbox Code Playgroud)

//控制器

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'=>'']);
}
Run Code Online (Sandbox Code Playgroud)


spr*_*ies 6

在不使用任何第三方库的情况下在yii2中创建依赖下拉列表就像yii1一样简单.您必须根据您的要求尝试以下编写的代码.使用gii为各个表创建模型,视图,控制器.

假设有两个像国家,城市一样的表,就像你写的一样.然后将以下代码写入一个控制器(如国家/地区)的视图文件中:

         <?php
                    use yii\helpers\ArrayHelper;
                    use yii\widgets\ActiveForm;
                    ?>
               <div>
            <?php
     $dataCountry=ArrayHelper::map(\app\models\Country::find()->
     asArray()->all(),'id', 'name');    
                  $form = ActiveForm::begin();
                echo $form->field($model, 'id')->dropDownList($dataCountry, 
                                     ['prompt'=>'-Choose a Name-',
                                         'class'=>'adjust',
                          'onchange'=>'
             $.post("'.Yii::$app->urlManager->createUrl('city/lists?id=').
           '"+$(this).val(),function( data ) 
                   {
                              $( "select#city" ).html( data );
                            });
                        ']); 

                $dataPost=ArrayHelper::map(\app\models\City::find()->
                 asArray()->all(), 'id', 'city');
              echo $form->field($model, 'id')
                    ->dropDownList(
                        $dataPost,   
                         ['id'=>'city',
                             'class'=>'adjust'
                             ]
                    );
                 ActiveForm::end(); 
               ?>
            </div>
Run Code Online (Sandbox Code Playgroud)

然后在另一个城市控制器中写下以下代码:

 <?php

namespace app\controllers;

class CityController extends \yii\web\Controller
{
        public function actionLists($id)
      {
         //echo "<pre>";print_r($id);die;
         $countPosts = \app\models\City::find()
         ->where(['country_id' => $id])
         ->count();

         $posts = \app\models\City::find()
         ->where(['country_id' => $id])
         ->orderBy('id DESC')
         ->all();

         if($countPosts>0){
         foreach($posts as $post){

         echo "<option value='".$post->id."'>".$post->city."</option>";
         }
         }
         else{
         echo "<option>-</option>";
         }

 }
}
Run Code Online (Sandbox Code Playgroud)

然后进入url它的工作原理!

编辑:固定网址建设.http请求现在可以使用了.