我是Yii的新手,如果有任何帮助,我将不胜感激。我需要创建一个带有多选投票的页面。我的模型是这样的:
民意调查问题:
id int
title varchar
轮询应答
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(); ?>
问题是,在控制器中,我只接收数组中的一个项。我不确定我做错了什么。
我的建议是,您需要一个额外的表单模型来做到这一点。您可以在上查看如何创建表单模型http://www.yiiframework.com/doc-2.0/guide-input-forms.html.
您创建的表单模型至少具有以下属性:
- 答案[]
- 指示答案[]
您可以将用户对该属性的输入保存到ActiveRecord模型中。
返回一个模型条目是正确的。在您的表单中,您正在创建一个单独的模型并将其传递给表单。
public function actionSurvey($user_id)
{
$model = [new PollResult];
// ...
return $this->render('survey', ['model' => $model]);
}
然后你可以期待一个单一的模型回来。
看看这个相关的问题,了解如何解决这个问题。父子关系模型使用Yii2.0复选框列表