Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dependent dropdown yii2. How to do?

Tags:

yii2

can I create a dependent dropdown in yii2?

I have two tables:

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

and have two methods in my model:

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 the first field:

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

and the second

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

I need to 'transmit' parent_id to controller and return city_list by AJAX (with JSON).

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

like image 762
Slip Avatar asked Nov 30 '22 11:11

Slip


1 Answers

use the krajee extension for dependent drop down

Details is here Krejee dependent dropdown for yii2

or follow following instructions:

Install the extension via composer:

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

In your view :

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

// THE 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'=>'']);
}
like image 196
Neophile Avatar answered Dec 25 '22 08:12

Neophile