lundi 24 avril 2017

Silex Form: use Checkboxes as array

When creating a normal form, you can have multiple checkboxes that work like an array. Example:

<form action="/action_page.php" method="get">
  <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
  <input type="checkbox" name="vehicle" value="Car" checked="checked"> I have a car<br>
  <input type="submit" value="Submit">
</form>

This gives you the ability to say:

Give me al the checked checkboxes with name of vehicle

That might be just the Bike or just the Car, but it can also be that both are selected. You can loop through them and do something with the data.

However, when I try to do something like this, Silex FormServiceProvider does not allow me to do something like this.

In my case, I use these lines of code:

foreach($user->data() as $player){
        $builder->add('player', CheckboxType::class, [
                    'constraints' => array(new Assert\NotBlank()),
                    'label' => $player->username,
                    'attr' => array('class' => 'input-field', 'value' => $player->username),
                    'label_attr' => array('class' => 'label')
            ]);
    }

A checkbox is made for every player in the game. I can select whether or not I want to add them to a team.

So after the form is submitted, I'd like to be able to do something like this:

$data = $form->getData();
foreach($data['player'] as $checked){
    //Add to the team
}

Can anyone explain me how to do this in Silex?




Aucun commentaire:

Enregistrer un commentaire