Loop in PHP to create a form dynamically

Asked

Viewed 451 times

-1

good pie.

I’m having trouble creating a php function to create a checkbox list.

I want to fill in the value attribute and HTML content of with information provided by PHP, through a loop.

The final HTML result needs to be similar to this:

<form name="form" method="post" action="form.php">
<p>
<label>php</label>
<input type="checkbox" name="genero[]" value="php"/>
</p>
<p>
<label>java</label>
<input type="checkbox" name="genero[]" value="java"/>
</p>
<p>
<label>mysql</label>
<input type="checkbox" name="genero[]" value="mysql"/>
</p>
<p>
<input type="submit" name="submit" value="Enviar"/>
</form>

2 answers

1

Oops beauty?

To make the loop you have to have a variable that already has the data you need, and then you can use the foreach for this, passing in value the attribute you want:

<form name="form" method="post" action="form.php">

<?php foreach($sua_variavel as $auxiliar) //neste caso, estarei pegando o valor de
//um array e atribuindo no VALUE da minha tag, mas você pode colocar 
//também uma variável que não seja um.

<p>
<label>php</label>
<input type="checkbox" name="genero[]" value="<?php echo $auxiliar['key']?>"/>
</p>
<p>
<label>java</label>
<input type="checkbox" name="genero[]" value="<?php echo $auxiliar['key']?>"/>
</p>
<p>
<label>mysql</label>
<input type="checkbox" name="genero[]" value="<?php echo $auxiliar['key']?>"/>
</p>

?>
<input type="submit" name="submit" value="Enviar"/>
</form>

Note that I left the form tags outside of PHP, because if you want something dynamic, I assume that everything inside this form will be sent to the PHP function that receives the form.

If you want to leave 1 different form for each loop, just leave the tag inside the loop, but keep in mind that you will need to change the action dynamically. (unless you would like to send only one information from one of the forms).

OBS: also take care with the Names, they must be different from each other (you will probably have to use a variable that concatenates each of them, so that when PHP receives the value it can differentiate). You can add an extra space in your array name="genero[1]", name="genero[2]", name="genero[3]"... To be different from one another.

1


Whereas you have a collection:

$collection = [
   [
    'value' => 'php',
    'label' => 'php'
   ],
   [
     'value' => 'java',
     'label' => 'java'
   ],
   [
     'value' => 'mysql',
     'label' => 'mysql'
   ]
];

Just do it:

<form name="form" method="post" action="form.php">
<?php if(count($collection)): ?>

<?php foreach($collection as $data):?>
  <p>
    <label><?php echo $data['label'];?></label>
    <input type="checkbox" name="genero[]" value="<?php echo $data['value'];?>"/>
 </p>
<?php endforeach;?>
<?php endif;?>
<input type="submit" name="submit" value="Enviar"/>
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.