2015-12-30 37 views
0

我是Yii的新手,希望对您有所帮助。 我需要创建一个具有多选轮询的页面。我的模型是这样的:在Yii2中创建调查表并提供多项选择答案

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) 

林不知道,如果Im做是正确的,我的控制器:

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

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

回答

0

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

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

然后,您可以期待返回单个模型。

看看这个相关的问题,你可以如何解决这个问题。 Utilising Yii2.0 checkboxlist for Parent-child relation models

+0

然后如何传递模型数组& –

+0

在我的答案中看到我的更新链接。 – crafter

1

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

创建的套用模式至少有这个属性:

  • 解答[]
  • indicated_answer []

,你可以从用户到该属性节约投入并把它们保存到你的ActiveRecord模型。

相关问题