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条)

报告相同问题?

悬赏问题

  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条