【问题标题】:How to make dependent dropdownlist in Yii2?如何在 Yii2 中制作依赖下拉列表?
【发布时间】:2017-04-27 10:58:43
【问题描述】:

我正在尝试在 Yii2 中创建一个依赖 dropDownList。我正在尝试使用 DepDrop Widget,但我不明白如何根据我的情况编辑代码。我有 1 个模型,在其中我需要制作类别下拉列表,根据 category_id,下一个 dropDownList 应该是 Item。 (F.e 如果我选择类别 1,则 Item 应该是 Item1 等等)。

我猜这个扩展只能做相同型号的下拉菜单?我是 Yii2 的新手,所以。

我的view 文件:

<div class="site-create">

<?php $form = ActiveForm::begin(); ?>

    <?= $form->field($model, 'code') ?>
    <?= $form->field($category, 'id')->dropDownList($category, ['id'=>'category-id']); ?>
    <?= $form->field($item, 'subcat')->widget(DepDrop::Item(), [
         'options'=>['id'=>'item-id'],
        'pluginOptions'=>[
         'depends'=>['category-id'],
        'placeholder'=>'Select...',
        'url'=>Url::to(['/site/subcat'])
        ]
   ]); ?>

我的$model$category$item 的型号不同。我将这些变量设置为在操作中使用不同的模型

这是我的action

    public function actionSubcat() {
    $category = new Category();
    $item = new Item();
    $out = [];
    if (isset($_POST['depdrop_parents'])) {
        $parents = $_POST['depdrop_parents'];
        if ($parents != null) {
            $cat_id = $parents[0];
            $out = self::getSubCatList($cat_id); 
            echo Json::encode(['output'=>$out, 'selected'=>'']);

        return $this->render('create', [
                'category' => $category,
                'item' => $item,
            ]);
        }
    }
    echo Json::encode(['output'=>'', 'selected'=>'']);
}
}

现在我收到$category 变量未定义的错误消息。有人可以解释一下我做错了什么吗?

【问题讨论】:

    标签: yii2


    【解决方案1】:

    我建议使用 knockoutjs 来执行此操作。 i answered a similar question here 淘汰赛example is here(类别>产品)

    html:

    <select data-bind="options: data, value: selected, optionsText: 'title', optionsCaption: '---'"></select>
    <select data-bind="options: dependent"></select>
    

    javascript:

    <script>
        function viewmodel() {
            var self = this;
    
            this.data = [
                { title: 'title a', items: ['a1', 'a2', 'a3'] },
                { title: 'title b', items: ['b1', 'b2', 'b3'] },
                { title: 'title c', items: ['c1', 'c2', 'c3'] }
            ];
    
            this.selected  = ko.observable();
            this.dependent = ko.computed(function() {
                return ((self.selected() || {}).items || []);
            });
    
        }
    
        $(document).ready(function() {
            ko.applyBindings(new viewmodel());
        });
    </script>
    

    您仍然可以使用$form-&gt;field,只需将'data-bind' 属性添加为inputOption。 如果你想使用字段的默认值,Json::encode 那些键值对并像这样创建视图模型:

    ko.applyBindings(new viewmodel(<?= Json::encode($data) ?>));
    

    使用这些参数是 javascript 体力劳动

    【讨论】:

      【解决方案2】:

      实际上您不需要任何小部件或插件。在 yii2 中你可以很容易地做 Dependent Dropdown list 这里是例子:

      echo $form->field($search,'category')->dropDownList(
          ArrayHelper::map(
              \app\models\Category::find()->all(),
              'id','name'
          ),
          [
              'prompt' => Yii::t('app','choose_city'),
              'onchange'=>'
              $.get( "'.Yii::$app->urlManager->createUrl('site/dropdown?id=').'"+$(this).val(), function( data ) {
              $( "select#subcat" ).html( data );
              })'
          ]
      );
      echo $form->field($search, 'sub_category', ['inputOptions'=>['id'=>'subcat',]])->dropDownList([]);
      

      之后,您需要为返回操作创建操作。示例:

       public function actionDropdown($id)
      {
          $countPosts = \app\models\SubCategory::find()
              ->where(['category_id' => $id])
              ->count();
      
          $posts =  \app\models\SubCategory::find()
              ->where(['category_id' => $id])
              ->orderBy('name ASC')
              ->all();
          echo "<option value=''>-</option>";
          if($countPosts>0){
              foreach($posts as $post){
                  echo "<option value='".$post->id."'>".Yii::t('app',$post->name)."</option>";
              }
          }
      
      }
      

      仅此而已。

      【讨论】:

        【解决方案3】:
        <?= $form->field(**$category**, 'id')->dropDownList(**$category_dropdown**, ['id'=>'category-id']); ?>
        

        两个名字都不一样:

        $category = your model
        $category_dropdown = arrayhelper variable in your action
        like below
            $transactioncategory = ArrayHelper::map(Transactioncategory::find()->all(), 'id', 'transaction_category');
        

        【讨论】:

          猜你喜欢
          • 2014-03-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-24
          • 1970-01-01
          • 2020-12-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多