Search code examples
phpyii2dropdown

Possible for dependent drop down in one table?


I am new to yii and i am trying to use dependent drop down list as tutorial

My idea is to create a dependent drop down list by one table:

IntakeDetails [id, course_name, intake_no]

Inside the table can fill in different intakes with the same course name. And then i using another form with the drop down (course name) and (intake). The (intake)drop down will show the values that selected from the drop down (course name).

My form:

<?=  $form->field($model, 'course_name')->dropDownList(
ArrayHelper::map(IntakeDetails::find()->all(), 'course_name', 'course_name'),
[
    'prompt'=>'Select course',
    'onchange' => '
        $.post(
            "' . Url::toRoute('getoperations') . '", 
            {id: $(this).val()}, 
            function(res){
                $("#requester").html(res);
            }
        );
    ',

]); ?>


<?= $form->field($model,'intake_no')->dropDownList(
[],
[
    'prompt' => 'Select intake',
    'id' => 'requester'
]); ?>

And the controller

  public function actiongetoperations()
  {
      if (Yii::$app->request->post('course_name')) {
          $operationPosts = IntakeDetails::find()
          ->select('intake_no')
          ->where(['course_name' => $model->course_name])
          ->count();
          
          if ($operationPosts > 0) {
              $operations = IntakeDetails::find()
              ->select('intake_no')
              ->where(['course_name' => $model->course_name])
              ->all();
              foreach ($operations as $operation)
                  echo "<option value='" . $operation->intake_no. "'>" . $operation->intake_no . "</option>";
          } else
              echo "<option>-</option>";
              
      }
  

The form didn't give any values from the selected drop down even i have the values inserted to the database tables. So, it is possible to use it like that? If yes , please let me know. I am willing to learn. Thanks.


Solution

  • can you show your controller's behavior action? does it reaches to actiongetoperations ? whats response from action? it should be

       public function behaviors()
        {
            return [
                'access' => [
                    'class' => AccessControl::className(),
                    'rules' => [
                        [
                            'actions' => [
                                'get-operations']
                        ......
    
     and actionGetOperations(){}