2017-07-03 57 views
0

我有關於公民的國家和城市的數據。這些數據使用js顯示在下拉列表中。當我嘗試更新它們時,下拉列表在保存之前不顯示數據。如何解決它。 我的代碼是:如何在下拉列表中設置值yii2

<?= $form->field($organization, 'country_id')->dropDownList([],[ 
           'prompt' => '---', 
           'onchange' => ' 
            $.get("../citizeninfo/city?id='.'"+$(this).val(), function(data){ 
            $("select#training-city_id").html(data); 
            });' 
            ]) ?> 

<?= $form->field($organization, 'city_id')->dropDownList([], ['prompt' => '---']) ?> 

回答

0

您可以用這種方式:

城市模型

public static function getCityByCountry($countryId) 
{ 
    $cities = self::find() 
     ->where(['country_id' => $countryId]) 
     ->select(['name']) 
     ->indexBy('id') 
     ->orderBy(['name' => SORT_ASC]) 
     ->column(); 

    return $cities; 
} 

form.php的

<?= $form->field($organization, 'city_id')->dropDownList(City::getCityByCountry($organization->country_id), ['prompt' => '---']) ?> 

country_id做同樣的事情。
你也可以在你的jQuery中調用相同的函數來獲取所選國家的城市。

0

集Vaue:

<?= $form->field($model, 'sex')->dropDownList(
      ['0' => 'Male', 
      '1' => 'Female'] 
    ) ?>