Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of a group of items inside an HTML form

Tags:

html

forms

I'm trying to create a form along the lines of the following (I am aware that this is not valid HTML, but it hopefully illustrates what and why I am trying to do this):

<form method="post" action="test.php">
    <input type="text" name="teamName">
    <br />Players:
    <grouping name="players[]">
        <input type="text" name="firstName"><br />
        <input type="text" name="lastName"><br />
    </grouping>
    <input type="submit" value="submit">
</form>

Through javascript, I would then add the grouping element as many times as needed. When the form is submitted, I could then access the items in the grouping element as follows:

foreach ($players as $player) {
    $fName = $player->firstName;
    $lName = $player->lastName;
}

That is, before I start, I don't know how many players will be on the team, but I know what a player looks like. I want to keep this all on one screen, so that the user can add players to their team on one page, and I want to be able to add the grouping of fields as a group. However, I would also like that grouping to be stored as an array, instead of doing something like:

<form method="post" action="test.php">
    <input type="text" name="teamName">
    <br />Players:
    <input type="text" name="firstName[]"><br />
    <input type="text" name="lastName[]"><br />
    <input type="submit" value="submit">
</form>

which would mean that I could iterate through the individual elements in the grouping, but not through the grouping as a whole.

Any ideas how I might accomplish this?

like image 297
Elie Avatar asked Oct 19 '25 16:10

Elie


1 Answers

Looking at your structure, though, I'd recommend going for a more robust array structure:

foreach ($players as $i => $player) {
    $fName = $player->firstName;
    $lName = $player->lastName;

    echo '<input type="text" name="players['.$i.'][firstName]" value="'.$fName.'" />';
    echo '<input type="text" name="players['.$i.'][lastName]" value="'.$lName .'" />';

}

When you submit this, you'd get:

players => Array(
  [0] => Array (
    firstName => a name,
    lastName => another name,
  ),
  [1] => Array (
    firstName => a name,
    lastName => another name,
  ),
etc...
)

Alternatively, rather than generating $i in the foreach statement, you could do an incrementing $i++ in the last input field, but I find for debugging purposes it's often nice to know which index your using from the original array.

I recommend this approach over your question's example, as it also allows you to do a count/iterate through $_POST['players']

Hope this helps

like image 167
Joseph Fung Avatar answered Oct 21 '25 07:10

Joseph Fung