2016-08-07 110 views

回答

1

您CAND形式此代碼

<?php $Country= ArrayHelper::map(Country::find()->all(),'id', 'country_name');?> 
<?php echo $form->field($model, 'country')->dropDownList($Country, 
    ['prompt'=>'-Choose a Category-', 
     'onchange'=>' 
     $.post("'.urldecode(Yii::$app->urlManager->createUrl('country/lists&id=')).'"+$(this).val(), function(data) { 
      $("select#city_id").html(data); 
     }); 
    ']); ?> 
<?php echo $form->field($model, 'city')->dropDownList(   
    ['prompt'=>'-Choose a Sub Category-'], 
    ['id'=>'city_id'] 
);?> 
<div class="form-group"> 
    <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?> 
</div> 
<?php ActiveForm::end(); ?> 

,並創建控制器列表行動

public function actionLists($id) 
{ 
    $sql = "select * from city where country_id ='$id' "; 
    $models = City::findBySql($sql)->asArray()->all(); 
    if(sizeof($models) >0) 
    { 
     echo "<option value="">-Choose City-</option>"; 
     foreach($models as $model) 
     { 
      echo "<option value='".$model['id']."'>".$model['city_name']."</option>"; 
     } 
    } 
    else 
    { 
     echo "<option>-Choose a Sub City-</option><option></option>"; 
    } 

}