V
V
Victor Umansky2017-04-12 18:29:19
Yii
Victor Umansky, 2017-04-12 18:29:19

Yii2 - Select data that depends on another selected value?

Hello!
I have a table RegionCity, this table contains regions and cities. I need to do so, when the user
selects an area from the drop-down list, then cities in the other drop-down list should be pulled up to this area.
How to implement this without reloading the page, I was told that jquery is needed?
DB:
id | parent_id | name_ru |
Model:

protected function buildTreeRegionCity($data, $rootID = 0)
    {
        $tree = [];
        foreach ($data as $id => $node) {
            if ($node['parent_id'] == $rootID) {
                unset($data[$id]);
                $node['childs'] = RegionCity::buildTreeRegionCity($data, $node['id']);
                $tree[] = $node;
            }
        }
        return $tree;
    }

    public static function getAllRegionCity()
    {
        $data = self::find()->asArray()->all();
        return RegionCity::buildTreeRegionCity($data);
    }

view:
<?php $form = ActiveForm::begin() ?>

        <div class="form-group field-profile-region">
            <label class="control-label" for="profile-region">Выбрать область</label>
            <select id="profile-region" class="form-control" name="Profile[region]">
                <?php foreach ($regionCity as $region): ?>
                    <option value="<?= $region['id'] ?>"><?= $region['name_ru'] ?></option>

                <?php endforeach; ?>
            </select>
        </div>

        <div class="form-group field-profile-region">
            <label class="control-label" for="profile-region">Выбрать город</label>
            <select id="profile-region" class="form-control" name="Profile[region]">
                <?php foreach ($regionCity as $region): ?>
                    <?php foreach ($region['childs'] as $city): ?>
                        <option value="<?= $city['id'] ?>"><?= $city['name_ru'] ?></option>
                    <?php endforeach; ?>
                <?php endforeach; ?>
            </select>
        </div>

        <?= '<br><br>' . Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
        <?php $form = ActiveForm::end() ?>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-04-12
@Uman

Good afternoon.
I took the example from my project, just change the data, paths and the like.
_form.php file

<div class="col-lg-6">
        <?= $form->field($model, 'country_id')->dropDownList(Countries::getActiveCountry(), /* доступные к просмотру страны, в модели стран.*/
                                                 [
                                                     'prompt' => AirlinesModule::t('module','AIRLINES_PROMPT_FORM'),
                                                     'onchange' => '
                                                         $.post(
                                                          "'. Url::toRoute('default/ajax') .'",
                                                          {id: $(this).val()},
                                                          function(data){
                                                            $("select#city").html(data).attr("disabled", false)
                                                          }
                                                         )
                                                     '
                                                 ]
                                                ) ?>
    </div>
    <div class="col-lg-6">
        <?= $form->field($model, 'city_id')->dropDownList(Cities::getActiveCity(),/* Доступные к просмотру города в модели городов*/
              [
                  'prompt' => AirlinesModule::t('module', 'AIRLINES_PROMPT_FORM'),
                  'id' => 'city',
                  'disabled' => $model->isNewRecord ? true : false
              ]
            ) ?>
    </div>

In the controller DefaultController.php
public function actionAjax()
    {
        if(Yii::$app->request->isAjax){
            $id = (int)Yii::$app->request->post('id');
            $this->option = "<option value='0'>" . AirlinesModule::t('module', 'AIRLINES_PROMPT_FORM') . "</option>";

            $cities = Cities::find()
                              ->where(['status' => Cities::STATUS_ACTIVE])
                              ->andWhere('country_id=:id',[':id' => $id])
                              ->orderBy('city')
                              ->all();
            foreach ($cities as $city){
                $this->option .= '<option value="' . $city->id . '">' . $city->city . '</option>';
            }

        }
        return $this->option;
    }

ps
Correctly said, if without reloading the page, then ajax, using jquery, the task is simplified.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question