How to create a dropdown dependent on another dropdown in yii2?

我的未来我决定 提交于 2019-12-12 03:25:22

问题


I have two api's: 1: returns all the industries, 2: returns all the industry category(based on industry id).

I need two dropdowns, one dependent on other. On selecting industry 2nd dropdown should show only relevant categories.

Thanks in advance.


回答1:


I got it. I have simply used ajax which posts the value from one dropdown and sends the data to an action which returns the data and i am simply putting those values to my other drop down. :)




回答2:


<?= $form->field($model, 'industryId')->dropDownList($industry, 
                                             ['prompt'=>'Select Industry',
                                'onchange'=>'
                                    $.get( "'.Url::toRoute('/site/category').'", { id: $(this).val() } )
                                        .done(function( data ) {
                                            $( "#'.Html::getInputId($model, 'industryName').'" ).html( data );
                                        }
                                    );
                                ','class' => 'form-control'    
                            ]
                    ); ?>
<?= $form->field($model, 'industryName')
                ->dropDownList(

                    ['prompt'=>'Select category','class' => 'form-control']);
            ?> 



回答3:


_form.php

  <?php 
    use yii\helpers\Html;
    use yii\widgets\ActiveForm;
    use yii\helpers\ArrayHelper;
    use app\models\Category;
    ?>

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

     $model = Category::find()->select('id,name')->orderBy('name asc')->all();
     $listData = ArrayHelper::map($model, 'id', 'name');
     <?= $form->field($model, 'industryId')->dropDownList($listData, 
                                                     ['prompt'=>'Select Category',
                                        'onchange'=>'
                                            $.get( "'.Url::toRoute('/category/subcats').'", { id: $(this).val() } )
                                                .done(function( data ) {
                                                    $( "#'.Html::getInputId($model, 'sub_category').'" ).html( data );
                                                }
                                            );
                                        ','class' => 'form-control'    
                                    ]
                            ); ?>
        <?= $form->field($model, 'sub_category')
                        ->dropDownList(

                            ['prompt'=>'Select sub cat','class' => 'form-control']);
                    ?> 

 ----



回答4:


You can use this extension. You can find explanation of plugin on its guide page.



来源:https://stackoverflow.com/questions/36500793/how-to-create-a-dropdown-dependent-on-another-dropdown-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!