Hello, I’m making linked lists of regional and city selection in Yii2

View // select region

$items = \yii\helpers\ArrayHelper::map(\app\models\Region::find()->all(), 'id', 'name'); echo $forms->field($models, 'obl')->widget(kartik\select2\Select2::className(),[ 'data' => $items, 'options' => ['onchange' => '$.post( "'. yii\helpers\Url::toRoute('site/lists?id=').'"+$(this).val(), function( data ) { $( "select#name" ).html( data );}); '], 

// select city

  $item = \yii\helpers\ArrayHelper::map(\app\models\City::find()->all(), 'id', 'name'); echo $forms->field($models, 'city')->widget(kartik\select2 \Select2::className(),[ 'data' => $item, 'options' => ['id' => 'name'], 

Controller

public function actionLists ($ id) {

  $countCity = \app\models\City::find() ->where(['region_id'=>$id]) ->count(); $cityes = \app\models\City::find() ->where(['region_id'=>$id]) ->all(); if($countCity>0){ foreach ($cityes as $city){ echo "<option value='".$city->id."'>".$city->name."</options>"; } } else { echo "<options></options>"; } 

The problem lies in the fact that on the page I have two different forms in which these lists are found, and if everything works as it should in the first form, then in the second form, the city selection field is not displayed at all. If you remove 'id' => 'name' from the city selection, then the field becomes visible, but of course the connection with the list of regions disappears. Is it possible to somehow force the second pair of regions and cities to work without resorting to third-party extensions?

    1 answer 1

    id is a unique field and you cannot assign one id to two different elements on the same page. It is necessary to do that in the first case the id would be “name-1” and in the second “name-2”