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

时间:2016-02-25 05:53:54

标签: php model-view-controller yii tabular

我正在使用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

我正在尝试创建一个表单,并且无可否认地为所有可能的问题收集答案。

文件:ResponseController

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中。

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

1 个答案:

答案 0 :(得分:0)

我设法解决了我的“循环”问题:

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

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