2015-12-30 38 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模型。

相關問題