I need a dropDownList to show a list of cities depending on the country selected in another dropdown list.As far I understand, the only way to do it is to pass country’s id back to the view via ajax (having something like dropDownList(ArrayHelper::map($resorts_model->find()->where([‘country’ => Yii::$app->request->get(‘cnt_id’)])->orderBy(“name ASC”)->all(), ‘id’, ‘name’) ). The problem is I can’t get it all worked.
The view:
/…/
//countries
<?= $complex_form->field($countries_model, ‘name’, [‘template’ => ‘{input}’,
‘options’=>[‘tag’=>false]])->dropDownList(ArrayHelper::map($countries_model->find()->orderBy(“name ASC”)->all(), ‘id’, ‘name’),
[‘tabindex’=>’-1’, ‘class’=>‘SumoUnder’, ‘id’=>‘sumo-direction’])->label(false) ?>
/…/
//cities
<?= $complex_form->field($resorts_model, ‘name’, [‘template’ => ‘{input}’,
‘options’=>[‘tag’=>false]])->dropDownList(ArrayHelper::map($resorts_model->find()->orderBy(“name ASC”)->all(), ‘id’, ‘name’), [‘tabindex’=>’-1’, ‘class’=>‘SumoUnder’, ‘id’=>‘sumo-direction-city’])->label(false) ?>
/* with having the 1st list changed here’s supposed to be something like dropDownList(ArrayHelper::map($resorts_model->find()->where([‘country’ => Yii::$app->request->get(‘cnt_id’)])->orderBy(“name ASC”)->all(), ‘id’, ‘name’) but in the same list /
/…*/
JS. And here’s another problem - requesr error 400 pops up despite of the token being passed.
//on ready
$("#sumo-direction").on("change", function(){
/*.....*/
var param = $('meta[name=csrf-param]').attr("content");
var token = $('meta[name=csrf-token]').attr("content");
//console.log(param, token);
$.ajax({
type: "POST",
url: 'index.php?r=site%2forder', //been tried here in different ways...
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { cnt_id: cnt_value, param: token}
}).done(function(msg){console.log('success', msg);}).fail(
function(jqXHR, textStatus) {console.log(textStatus, jqXHR.responseText);});
});
Controller:
/*............*/
public function actionOrder()
{
$model = new OrderForm();
$countries_model = new Countries();
$resorts_model = new Resorts();
$hotels_model = new Hotels();
$model->created_at = date('Y-m-d H:i:s');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->sendMail(Yii::$app->params['adminEmail']);
Yii::$app->session->setFlash('contactFormSubmitted');
return $this->refresh('#form');
}
return $this->render('contact', [
'model' => $model,
'countries_model' => $countries_model,
'resorts_model' => $resorts_model,
'hotels_model' => $hotels_model,
]);
}