Silex:在Formbuilder中使用Checkboxes作为数组

时间:2017-04-24 16:15:29

标签: php forms checkbox silex

创建普通表单时,您可以使用多个类似于数组的复选框。例如:

<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>

这使您能够说:

  

给我选中带有车辆名称的复选框

那可能只是自行车或只是汽车,但它也可以是两者都被选中。您可以遍历它们并对数据执行某些操作。

然而,当我尝试做这样的事情时,Silex FormServiceProvider不允许我做这样的事情。

就我而言,我使用以下代码行:

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')
            ]);
    }

为游戏中的每个玩家制作一个复选框。我可以选择是否要将它们添加到团队中。

所以在提交表单后,我希望能够做到这样的事情:

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

有谁能解释我如何在Silex中做到这一点?

1 个答案:

答案 0 :(得分:0)

I have found my solution. I've been using the wrong Input type. When I use the choice type. It works fine:

$players = [];
foreach($user->data() as $player){
    $array = array($player->username => $player->username);
    array_push($players, $array);
}

$builder->add('player', ChoiceType::class, [
        'constraints' => array(new Assert\NotBlank()),
        'choices' => $players,
        'choice_attr' => function($val, $key, $index) {
            return ['class' => 'input-field'];
        },
        'multiple' => true,
        'expanded' => true
]);