Yii,表格输入的循环表单字段

Yii, Looping form fields for Tabular Input

我使用的是Yii Framework 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,
    ));
}

这是我遇到问题的地方:

文件:response/_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 中。

我好像找不到有效解决这个问题的方法。有人可以指导我吗?

我通过以下方式解决了我的 "loop" 问题:

文件:response/_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; ?>

希望有一天,这会对某人派上用场。