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?
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'=>'']);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With