1

我正在尝试在 yii2 basic 中创建一个依赖下拉列表,但它没有按预期工作。下面是创建下拉菜单的代码

 <?= $form->field($model,'grp_name')->dropDownList(
        ArrayHelper::map( Maingroup::find()->all(), 'id', 'name'),
        [
            'prompt'=>'Select your group',
            'onchange'=>'   $.post( "index.php?r=memberdetail/lists&id='.'"+$(this).val(), function( data ) {
                                            $( "select#memberdetail-sub_grp" ).html( data );
                                        });'
        ]); ?>
    <?= $form->field($model,'sub_grp')->dropDownList(
        ArrayHelper::map(NewGroup::find()->all(), 'id', 'group_num'),
        [
            'prompt'=>'Select your sub-group',

        ]); ?>

我在 memberdetail 控制器中的列表操作是

 public function actionLists($id)
    {
        $countsubgroup = NewGroup::find()
            ->where(['group_name' => $id])
            ->count();

        $subgroup = NewGroup::find()
            ->where(['group_name' => $id])
            ->all();

        if ($countsubgroup > 0) {
            foreach ($subgroup as $name) {
                echo "<option value='" . $name->id . "'>" . $name->group_num . "</option>";
            }
        } else {
            echo "<option> - </option>";
        }

    }

实际发生的是我认为这个问题,因为它不会进入 memberdetail 控制器,也不会调用公共函数 actionLists($id)在此处输入图像描述

4

2 回答 2

1

创建依赖下拉列表的简单方法

首先DependentController.php在您的controller文件夹中创建

<?php    
namespace app\controllers;
use yii\helpers\Html;
use Yii;

class DependentController extends \yii\web\Controller
{
    public function actionGetsubgroup($id)
    {
        $rows = NewGroup::find()->where(['group_name' => $id])
        ->all(); 
        echo "<option value=''>---Select State---</option>";     
        if(count($rows)>0){
            foreach($rows as $row){
                echo "<option value='$row->id'>$row->group_num</option>";
            }
        }
        else{
            echo "";
        } 
    }
}

你的 _form.php

<?= $form->field($model,'grp_name')->dropDownList(ArrayHelper::map( Maingroup::find()->all(), 'id', 'name'),
[
   'prompt'=>'Select your group',
   'onchange'=>'$.get( "'.Url::toRoute('dependent/getsubgroup').'", { id: $(this).val() } ).done(function( data ) { $( "#'.Html::getInputId($model,'sub_grp').'" ).html( data ); } );'    
]); ?>

 <?php if(!empty($model,'sub_grp')) : ?>
    <?= $form->field($model,'sub_grp')->dropDownList(ArrayHelper::map(NewGroup::find()->all(), 'id', 'group_num'), ['prompt' => '---Select Sub-Group---']);  ?>
<?php else : ?>
    <?= $form->field($model,'sub_grp')->dropDownList([], ['prompt' => '---Select Sub-Group---']);  ?>
<?php endif; ?>
于 2016-02-18T07:03:56.127 回答
0

如果您启用了漂亮的 url,并且没有在您的站点 url 中获取 index.php,那么您必须更改 post 操作,如下所示。

'onchange'=>'   $.post( "lists?id='.'"+$(this).val(), function( data ) {
                                        $( "select#memberdetail-sub_grp" ).html( data );
                                    });'

如果不是,请说明您在 400 bad request 中遇到的确切错误

于 2016-02-18T13:03:43.133 回答