4

我可以在 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, 'id', 'name_city','country_id');
}

我有第一个字段:

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

第二个

<?= $form->field($model, 'city')->dropDownList($model->cityList);

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

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

4

4 回答 4

11

使用 krajee 扩展进行依赖下拉

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

或遵循以下说明:

通过 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'=>'']);
}
于 2014-06-03T11:02:25.047 回答
8

在 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>

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

 <?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>";
         }

 }
}

然后运行到 url 它的工作原理!

编辑:固定网址建设。http 请求现在可以工作了。

于 2014-08-23T10:37:46.763 回答
2

您可以在没有任何小部件的情况下手动执行此操作:

使您的活动形式如下:

<?=  $form->field($model, 'nameofyourmodel')->dropDownList(
    ArrayHelper::map(\app\models\nameofyourmodel::find()->all(), 'id', 'name'),
    [
        'prompt'=>'smth',
        'onchange' => '
            $.post(
                "' . Url::toRoute('getoperations') . '", 
                {id: $(this).val()}, 
                function(res){
                    $("#requester").html(res);
                }
            );
        ',

    ]
); ?>

这里是从第一个模型接收 id 的第二种形式:

 <?= $form->field($model,'nameofyourmodel')->dropDownList(
    [],
    [
        'prompt' => 'smth',
        'id' => 'requester'
    ]
); ?>

最后一个动作是在控制器中创建一个功能来匹配 2 个 id 并将它们发送到您的模型:

public function actionGetoperations()
{
    if ($id = Yii::$app->request->post('id')) {
        $operationPosts = \app\models\firstmodel::find()
            ->where(['id' => $id])
            ->count();

        if ($operationPosts > 0) {
            $operations = \app\models\secondmodel::find()
                ->where(['firstmodelid' => $id])
                ->all();
            foreach ($operations as $operation)
                echo "<option value='" . $operation->firstmodelid. "'>" . $operation->name . "</option>";
        } else
            echo "<option>-</option>";

    }
}
于 2018-10-04T10:30:26.517 回答
0

上面的代码不能正常工作。行中有错误

$.post("'.Yii::$app->urlManager->createUrl('city/lists&id=').'"+$(this).val(),function( data ) 

控制台显示错误:未找到(#404):无法解析请求:子类别/列表&id=54

有什么解决方案吗?我的控制器如下所示

public function actionLists($id)
      {
         $posts = SubCategory::find()
         ->where(['category_id' => $id])
         ->orderBy('id DESC')
         ->all();

         if($posts){
         foreach($posts as $post){

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

    }

当我从 url 中删除 id 并将其硬编码到控制器中时,它可以正常工作。

我找到了解决方案,请按以下方式更改您的视图

 <?= $form->field($model, 'category_id')->dropDownList($data,['prompt'=>'-Choose a Category-',

                                                            'onchange'=>'
             $.get( "'.Url::toRoute('product/catlists').'", { id: $(this).val() } )
                            .done(function( data )
                   {
                              $( "select#product-sub_categoryid" ).html( data );
                            });
                        ']); ?> 

和这样的控制器

public function actionCatlists($id)
    {
        $mymodel = new Product ();
        $size = $mymodel->modelGetCategory ( 'product_sub_category',$id );
        if($size){
            echo '<option value="">Choose Sub category</option>';
            foreach($size as $post){
                echo "<option value='".$post['id']."'>".$post['name']."</option>";
            }
        }
        else{
            echo '<option value="0">Not Specified</option>';
        }

    }

不要忘记将其包含在您的视图中

use yii\helpers\Url;
于 2015-01-20T08:52:07.313 回答