can I create a dependent dropdown in yii2?
I have two tables:
\'id\',\'name_country\"
\'id\',\'name_city\',\'country_id\'
and have
creating dependent dropdown in yii2 without using any third party libraries is quite as simple as yii1. you have to try following code written below as per your requirements. use gii to create models,views, controller for respective tables.
suppose there r two table like country, city as u written. then write the following code into views file for one controller(like country):
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();
?>
and after this in another controller for city write following code as:
";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 "";
}
}
else{
echo "";
}
}
}
then run into url it works!
edit: fixed url construction. http requests will now work.