我有一个表格,可以从调查中提出问题和答案。用户可以选择5个单选按钮 - 选择问题的答案。它们是数组,关键是question_id
- 每个问题都有这5个单选按钮,它们在这个键上有所不同。你能帮我进行表单验证吗?
现在,如果您选择其中一个问题的答案,则表单提交。只有在所有问题都有答案时才必须提交。这是我的观点:
<html>
<head></head>
<body>
<?php
$survey_id = $this->uri->segment(3);
$question_id = $this->uri->segment(4);
$att=array('id'=>'form');
echo form_open('index/survey_fill/' .$survey_id .'/'. $question_id , $att);
echo "<table border="0" id='questionsTable' >";
echo "<tr><th>Въпрос</th></tr>";
echo validation_errors();
$index = 0;
foreach ($question as $row)
{
echo "<tr id='$index'>";
$index++;
?>
<td>
<?php echo "$row->question"; ?><br/>
<?php echo "<input type='hidden' name='question_id' value='$row->question_id' />"; ?>
<?php
$data=array(
'name' => 'answer['.$row->question_id.']',
'value' => '5',
'class' => 'answer'
);
echo "<input type='hidden' name='survey_id' value='$row->survey_id'>";
echo form_radio($data);
echo " 5 ";
$data=array(
'name' => 'answer['.$row->question_id.']',
'value' => '4',
'class' => 'answer'
);
echo form_radio($data);
echo " 4 ";
$data=array(
'name' => 'answer['.$row->question_id.']',
'value' => '3',
'class' => 'answer'
);
echo form_radio($data);
echo " 3 ";
$data=array(
'name' => 'answer['.$row->question_id.']',
'value' => '2',
'class' => 'answer'
);
echo form_radio($data);
echo " 2 ";
$data=array(
'name' => 'answer['.$row->question_id.']',
'value' => '1',
'class' => 'answer'
);
echo form_radio($data);
echo " 1 ";
?>
</td></tr>
<?php
}
?>
</table>
<?php echo "<input type='hidden' name='question_id' value='$row->question_id' />"; ?>
<?php echo '<input type="submit" id="button" name = "submit" value="Submit" class="btn btn-success">';
?>
</form>
</div>
</body>
</html>
我的控制器是:
public function survey_fill()
{
$this->form_validation->set_rules('answer[]', 'Answer', 'required');
if ($this->form_validation->run()==FALSE)
{
$this->survey_show();
}
else
{
if ($this->user_model->survey_fill())
{
header('Refresh: 2; url=/survey/index.php/index/surveys_show');
}
else
{
$this->load->model('user_model');
$data['survey'] =$this->user_model->survey_show();
$data['dynamic_view'] = 'survey_show';
$data['menu']=$this->menu_model->get_menu();
$this->load->view('templates/main',$data);
}
}
}
答案 0 :(得分:1)
两种方式:
1)在数据数组中设置必需属性,如
$data = array('name' => 'answer['.$row->question_id.']', 'required' => 'required');
2)为每个答案[$ question_id]变量设置表单验证。
foreach($questions as $question){
$this->form_validation->set_rules('answer['.$question->id.']', 'Question '.$question->id, 'required');
}
我坚持1。