在表单提交失败后,使用PHP重新填充所选选项值的最佳方式


Best way to use PHP to re-populate selected option value after a failed form submission?

我有这个表单,有10个下拉选项可供选择,最后在底部有一个复选框免责声明。

例如,如果用户选择了所有10个答案,忘记勾选底部的免责声明框并点击提交,表单将返回一条错误消息,表示他们不同意免责声明,但他们之前选择的所有答案都消失了,他们必须重新选择。我试图找到一个最佳实践的方式来处理这个没有重复这么多的代码…

我有的,它工作,但它是疯狂的冗余,特别是如果我有100个问题。

<select name="question1" id="question1">
    <?php if ($question[0] == '0') {
        $first = 'selected="selected"';
        $second = '';
        $third = '';
        $fourth = '';
    } elseif ($question[0] == '1') {
        $first = '';
        $second = 'selected="selected"';
        $third = '';
        $fourth = '';
    } elseif ($question[0] == '2') {
        $first = '';
        $second = '';
        $third = 'selected="selected"';
        $forth = '';
    } elseif ($question[0] == '3') {
        $first = '';
        $second = '';
        $third = '';
        $forth = 'selected="selected"';
    }
    ?>
    <option value="0" <?php echo $first; ?>>Answer 1</option>
    <option value="1" <?php echo $second; ?>>Answer 2</option>
    <option value="2" <?php echo $third; ?>>Answer 3</option>
    <option value="3" <?php echo $fourth; ?>>Answer 4</option>
</select>

这只是一个问题,所以你可以想象我必须重复所有的问题。一定有更好的办法吧?

谢谢…

<option value="0" <?= ($question[0] == 0 ? "selected='selected'" : ""); ?>>Answer 1</option>
<option value="1" <?= ($question[0] == 1 ? "selected='selected'" : ""); ?>>Answer 1</option>
<option value="2" <?= ($question[0] == 2 ? "selected='selected'" : ""); ?>>Answer 1</option>
<option value="3" <?= ($question[0] == 3 ? "selected='selected'" : ""); ?>>Answer 1</option>

通常是吗?

据我所知,没有优雅的解决方案。我倾向于使用条件语句,例如;

<option value="0" <?=($question[0] == 0 ? ' selected' : '')?>>Answer 1</option>

我是这样做的:

$array_existing_values = array(3,5);
$array_options = array(1,2,3,4,5);
foreach(array_options as $value)
{
    $sel = null;
    if (in_array($array_existing_values,$array_options)
    {
         $sel = ' selected ';
    }
    $html_options .= "<option value='$value' $sel>$value</option>";
}

为季节添加验证

试试这个。让$questions为用户保留所有问题,如下所示:

$questions = array(
    // The first question
    array(
       'question' => 'The 1st question?'
       'answers' => array(
           'answer 1',
           'answer 2',
           'answer 3',
           'answer 4',
       )
    ),
    // The second question
    array(
        ...
    ),
    // etc
);

$answer包含用户的所有答案,如下所示:

$answer = array(1, 2, 3, 2, ... );

然后你可以像这样重新绘制你所有的问题:

foreach ($questions as $index => $question)
{
    echo "<p>" . $question['question'] ."</p>'n";
    echo "<select name='question" . $index . "' id='question" . $index . "'>'n";
    foreach ($question['answers'] as $value => $answer)
    {
        echo "<option value='" . $value . "' " . ($value == $answer[$index] ? "selected='true'" : "") . ">" . $answer . "</option>'n";
    }
    echo "</select>";
}