drxdai15012937753 2015-12-30 08:28
浏览 28
已采纳

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

Im new to Yii, and would appreciate any help. I need to create a page with multiple choice poll. My models look like this:

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

Sample question looks like:

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

Im not sure if Im doing it right, my controller:

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]);
}

View:

<?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(); ?> 

The problem is that in controller i receive only one item in array. Im not sure what am I doing wrong.

  • 写回答

2条回答 默认 最新

  • douzhi1937 2015-12-30 10:02
    关注

    It is correct that one model entry is returned. In your form, you are creating a single model and passing that to the form.

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

    You can then expect a single model back.

    Have a look at this related issue on how you can solve this. Utilising Yii2.0 checkboxlist for Parent-child relation models

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用