Yii2 dependent dropdown menu. How to make?

Is it possible to create a dependent dropdown menu in yii2?

I have two tables:

'id','name_country"
'id','name_city','country_id'

and in my model there are two methods:

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

and

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');
}

I have a first field:

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

and second

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

I need to "pass" parent_idto the controller and return city_listusing AJAX (with JSON).

How can i do this? I saw an example in Yii1 , but what about Yii2?

+1
source share
3 answers

use the krajee extension for the dependent drop down list

Details here are the Krejee dependent dropdown list for yii2

or follow these instructions:

Install the extension through the composer:

 $ php composer.phar require kartik-v/dependent-dropdown "dev-master"

In your opinion:

  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'])
    ]
]);

//CONTROLLER

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'=>'']);
}
+6
source

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, !

: URL. http- .

+3

.

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

shows an error: Not found (# 404): query cannot be completed: subcategory / lists & id = 54

is there any solution for this my controller looks below

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

    }

when I remove the id from url and hard-coded it to the controller, it works correctly.

I found a solution for this, please change your mind as follows

 <?= $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 );
                            });
                        ']); ?> 

and a controller like this

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>';
        }

    }

don't forget to include this in your view

use yii\helpers\Url;
0
source

Source: https://habr.com/ru/post/1621111/


All Articles