Welcome Guest, Not a member yet? Register   Sign In
Repopulating dynamic form fields
#1

[eluser]vertmonkee[/eluser]
I have a form where users will be able to enter animals they have seen. They enter the amount they have seen and I then use javascript to create the input boxes.

E.g. if the user enters 3 it will output
Code:
<input type="text/javascript" name="animalName[]" />
<br />
&lt;input type="text/javascript" name="animalName[]" /&gt;
<br />
&lt;input type="text/javascript" name="animalName[]" /&gt;

I am struggling with how to repopulate the fields if the form has errors.

Currently I set up my input properties as an array like so
Code:
$animal_name = array(
                'name'        => 'animalName',
                'id'        => 'animalName',
                'value'        => set_value('animalName'));

Then create the input like this

Code:
&lt;?php echo form_input($animal_name); ?&gt;

Has anyone done something similar to this before and how did you solve it?

Thanks for any help
#2

[eluser]Michael Wales[/eluser]
In your form:
Code:
&lt;?php
if count($_POST['animalName'] > 0) {
  // The user has submitted the form with some number of animalName elements
  $i = 0;
  foreach ($_POST['animalName'] as $animalName) {
    // Remember id attributes must be unique
    echo form_input(array(
      'name' => 'animalName[]',
      'id'   => 'animalName-' . $i,
      'value'=> set_value($animalName)));
    $i++;
  }
} else {
  // There are no animalName elements - just display one input and an icon to add more
}

You may be able to pull this off using the Input class - I rarely used array-based inputs so I haven't tried. Regardless, the $_POST array at this point in time has already been repopulated by the Input class if you are using Form Validation, so the end result is the same.
#3

[eluser]vertmonkee[/eluser]
Ok that seems straightforward enough rather than creating the array first then assigning it to the input you are doing it all as one.

Thanks for the quick reply




Theme © iAndrew 2016 - Forum software by © MyBB