Yii,循环表单字段用于表格输入


Yii, Looping form fields for Tabular Input

我正在使用 Yii 框架 1.1.17,并生成了三个模型:问题、答案选项和响应。

关系:

Table: Question (list of questions)
  id
  text
Table: AnswerOption (list of possible answers, associated with question)
  id
  question_id
  text
Table: Response (question and selected answer collector)
  id
  question_id
  answer_option_id
  text

我正在尝试创建一个表单,并诚然收集所有可能问题的答案。

文件:响应控制器

public function actionCreate()
{
    // load all questions and with it the possible answer Options
    $questions = Question::model()->findAll();
    // get number of questions
    $count = Question::Model()->count();
    $model = array();
    $i = 1;
    while ($i <= $count) {
        $model[] = Response::model();
        $i++;
    }
    if (isset($_POST['Response'])) {
        // 
   }
    $this->render('create', array(
        'model' => $model,
        'questions' => $questions,
    ));
}

这是我遇到问题的领域:

文件:响应/_form

<?php foreach($questions as $i=>$question): ?>
    <?php echo CHtml::activehiddenField($question,"[$i]id"); ?> <?php echo $question['text']; ?>
        <?php $options = CHtml::listData($question->answerOptions, 'id', 'text');?>
        <?php echo CHtml::activeDropDownList(AnswerOption::model(), "[$i]text", $options, array('empty' => 'Select answer...')); ?>
<?php endforeach; ?>

可能已经填充了我的问题和可能的答案,但我需要验证结果并将其保存在$model中。

似乎我找不到一种方法来有效地解决这个问题。 有人可以指导我吗?

我设法通过以下方式解决了我的"循环"问题:

文件:响应/_form

<?php $questions = Question::model()->findAll(); ?> 
<?php foreach ($questions as $j=>$question): ?>
    <div class="row">
        <?php echo $form->labelEx($model["$j"], "[$j]question_id"); ?>
        <?php echo $form->hiddenField($model["$j"], "[$j]question_id", array('value' => $question["id"])); ?>
        <?php echo $question['text']; ?>
    </div>
    <div class="row">
        <?php $options = CHtml::listData($question->answerOptions, 'id', 'text');?>
        <?php echo $form->labelEx($model["$j"], "[$j]answer_option_id"); ?>
        <?php echo $form->dropDownList($model["$j"], "[$j]answer_option_id", $options, array('empty' => 'Select answer...')); ?>
    </div>
<?php endforeach; ?>

希望有一天这会派上用场。