在Yii2中创建具有多项选择答案的调查表

时间:2015-12-30 08:28:44

标签: php forms yii2 yii-extensions yii2-advanced-app

我是Yii的新手,非常感谢任何帮助。 我需要创建一个包含多项选择轮询的页面。我的模型看起来像这样:

PollQuestion:

id int
title varchar

PollAnswer

 id char  //one letter - answer option
 title
 question_id //FK pool_question(id)

PollResult

user_id int
question_id int //FK poll_question(id)
answers         //will be stored like A,B,C
indicated_answer //alternaive answer specified by user

示例问题如下:

What do you think about us?
(checkbox)A. Good  
(checkbox)B.Bad  
(checkbox)C.Other (indicate) (textbox goes here)

我不确定我做得对,我的控制器:

public function actionSurvey($user_id)
{
     $model = [new PollResult]; 
     foreach($model as $model_item){
         $model_item->user_id= $user_id;

         if ($model_item->load(Yii::$app->request->post())) {
           //only one item received, why??
        }
     }

    return $this->render('survey', ['model' => $model]);
}

查看:

<?php $form = ActiveForm::begin(); ?> 
   <?php foreach(PollQuestion::find()->all() as $question) {?>
   <?php foreach($model as $model_item) { ?>

   <p><?=$question->title?></p>
   <?= Html::activeHiddenInput($model_item  , "user_id"); ?>
   <?= $form->field($model_item, 'answers')->checkboxList(ArrayHelper::map($question->pollAnswers, 'id', 'title')?>
   <?= $form->field($model_item, 'indicated_answer') ->textInput()?>
   <?php } }?>

   <div class="form-group"> 
   <?= Html::submitButton(Yii::t('app', 'Send'), ['class' => 'btn btn-success' ]) ?> </div> 

<?php ActiveForm::end(); ?> 

问题是在控制器中我只收到数组中的一个项目。我不确定我做错了什么。

2 个答案:

答案 0 :(得分:1)

我的建议是,你需要一个额外的表单模型来做到这一点。 您可以在http://www.yiiframework.com/doc-2.0/guide-input-forms.html上看到如何创建表单模型。

您创建的表单模型至少具有以下属性:

  • 答案[]
  • shown_answer []

您可以将用户的输入保存到该属性并将其保存到ActiveRecord模型中。

答案 1 :(得分:0)

返回一个模型条目是正确的。在您的表单中,您将创建一个模型并将其传递给表单。

public function actionSurvey($user_id)
{
     $model = [new PollResult];
       // ...
    return $this->render('survey', ['model' => $model]);
}

然后你可以期待一个模型。

看看有关如何解决此问题的相关问题。 Utilising Yii2.0 checkboxlist for Parent-child relation models