Looping form fields for Tabular Input

SOLVED.

I have three models:

Question, AnswerOption and Response.

The relationships:




Question (list of questions)

id

text


AnswerOption (list of possible answers, associated with question)

id

question_id

text


Response (question and selected answer collector)

id

question_id

answer_option_id

text



I am trying to create a form, and admittedly collect answers for all possible questions.

File: 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,

	));

}



This is the area that I am having trouble with:

File: 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; ?>



This is not correct, as I may have populated my questions and possible answers, but I need to validate and save the results in $model.

I am rather confused, as I have gone through loops within loops and I feeling rather loopy! :blink:

Thank you. :)

I managed to resolve my "loop" problem by:

File: 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; ?>



Hopefully, this would come in handy for someone, someday.