php在服务器端验证后在动态生成的字段中丢失字段值

I have a form with a select option that depending on its value will generate a x amount of select fields. user select #2 in field 1, 2 new self generated select fields will be added to the form. Belows for is the part of the form that generates dinamically the new select fields.

<?php
for ($i = 1; $i <= $num_of_selects; $i++) {
?>
    <select class="form-control" name="test[option<?= $i ?>]">
        <option value="1" <?php echo(($withErrors && $test->getoption1() == 1 ) ? 'selected' : ''); ?>>Test 1</option>
        <option value="2" <?php echo(($withErrors && $test->getoption1() == 2 ) ? 'selected' : ''); ?>>Test 2</option>
        <option value="3" <?php echo(($withErrors && $test->getoption1() == 3 ) ? 'selected' : ''); ?>>Test 3</option>
    </select>
<?php } ?>

All good until server side validation, after refreshing the form all select values are equal to the first values. The thing is that I cant remember how to dinamically change the $test->getoption1() , so in the newer select would become something like $test->getoption2(), $test->getoption3(), and so on...

With getoption1() I collect the select value that was set by the user for the first select. Basically what I need is to be able to change the 1 dinamically depending on $i as I do in:

name="test[option<?= $i ?>]"

it should look to something like

$test->getoption[$i]() == $i ;
  • You could create a string with the function names and use it in place of the function

  • If I understand your question correctly it would look like this:

    <?php
         for ($i = 1; $i <= $num_of_selects; $i++) {
         $functionOptions = 'getoption' . $i;
       ?>
         <select class="form-control" name="test[option<?= $i ?>]">
         <option value="1" <?php echo(($withErrors && $test->$functionOptions() == $i ) ? 'selected' : ''); ?>>Test 1</option>
         <option value="2" <?php echo(($withErrors && $test->$functionOptions() == $i ) ? 'selected' : ''); ?>>Test 2</option>
         <option value="3" <?php echo(($withErrors && $test->$functionOptions() == $i ) ? 'selected' : ''); ?>>Test 3</option>
    </select>
    

PHP offers a good amount of "Variable Functions" that seem really helpful in situations like this. In the above example PHP looks for a function that matches the string.

More here http://php.net/manual/en/functions.variable-functions.php

Another way to handle it is try create a function that handles the input like $test->selectOption($i) and that function could just handle it and return the 3 integers.