如何更新依赖下拉列表,如在yii2中创建数据

时间:2016-08-08 12:15:59

标签: jquery yii2

我添加此代码,此代码选择子类别下拉列表在upadte页面上不起作用,仅适用于创建页面。怎么做

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

 $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); 

 if($model->isNewRecord)
 {
 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(           
        ['prompt'=>'-Choose a Sub Category-'],
        ['id'=>'subcat_id']
    ); 
}
else
{
  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(           
        ['prompt'=>'-Choose a Sub Category-'],
        ['id'=>'subcat_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)
{
   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>";
    }

}

1 个答案:

答案 0 :(得分:0)

您正在使用yii 2.您可以使用kartik相关下拉列表。它很容易实现。请在此处阅读文档http://plugins.krajee.com/dependent-dropdown

这是演示: - http://plugins.krajee.com/dependent-dropdown/demo