2016-07-29 75 views
1

創建依賴下拉我使用此代碼對backend/views/_form.php如何yii2

<?php $CoursesCat = ArrayHelper::map(CoursesCat::find()->all(),'id', 'cat_name'); 
$CoursesSubcat = ArrayHelper::map(CoursesSubcat::find()->all(),'id', 'name'); 
$form = ActiveForm::begin(); ?> 

<?php 
echo $form->field($model, 'cat_id')->dropDownList($CoursesCat, 
     ['prompt'=>'-Choose a Category-', 
      'onchange'=>' 
      $.post("'.urldecode(Yii::$app->urlManager->createUrl('coursedetail/lists&id=')).'"+$(this).val(), function(data) { 
       $("select#subcat_id").html(data); 
      }); 
     ']); 


echo $form->field($model, 'subcat_id') 
    ->dropDownList( $CoursesSubcat   
     ['prompt'=>'-Choose a Sub Category-'], 
     ['id'=>'subcat_id'] 
    ); ?> 
+0

請給'CoursesSubcat'表結構 – vishuB

+0

此鏈接有助於您http://www.yiiframework.com/wiki/723/creating-a-dependent-dropdown-from-scratch-in-yii2/ – jithin

回答

1
public function actionLists($id) 
{ 
    echo $sql = "select * from courses_subcat where cat_id='$id' "; 
    $models = CoursesSubcat::findBySql($sql)->asArray()->all(); 
    //echo "<pre>";print_r($model);exit; 

    if(sizeof($models) >0){ 
     echo "<option>-Choose a Sub Category-</option>"; 
     foreach($models as $model){ 
      echo "<option value='".$model['id']."'>".$model['name']."</option>"; 
     } 
    } 
    else{ 
     echo "<option>-Choose a Sub Category-</option><option></option>"; 
    } 

} 
0

使用依賴降krajee延伸下來

詳細是這裏yii2 http://demos.krajee.com/widget-details/depdrop

或者按照Krejee依賴下拉以下說明:

通過作曲家安裝擴展:

$ php composer.phar require kartik-v/dependent-dropdown "dev-master" 

在你看來:

use kartik\widgets\DepDrop; 

//普通家長選擇

echo $form->field($model, 'cat')->dropDownList($catList, ['id' => 'cat-id']); 

//依賴下拉

echo $form->field($model, 'subcat')->widget(DepDrop::classname(), [ 
    'options' => ['id' => 'subcat-id'], 
    'pluginOptions' => [ 
     'depends' => ['cat-id'], 
     'placeholder' => 'Select...', 
     'url' => Url::to(['/site/subcat']) 
    ] 
]); 

//控制器

public function actionSubcat() { 
$out = []; 
if (isset($_POST['depdrop_parents'])) { 
$parents = $_POST['depdrop_parents']; 
if ($parents != null) { 
$cat_id = $parents[0]; 
$out = self::getSubCatList($cat_id); 
// the getSubCatList function will query the database based on the 
// cat_id and return an array like below: 
// [ 
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'], 
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>'] 
// ] 
echo Json::encode(['output'=>$out, 'selected'=>'']); 
return; 
} 
} 
echo Json::encode(['output'=>'', 'selected'=>'']); 
}