确定在控制器中选择了哪个Radio Typeform

问题描述 投票:1回答:2

我有一个表单,有多个RadioTypes来表示公告实体的类别。

$builder
->add('info', RadioType::class,
            [
                'label_attr' => ['class' => 'sr-only'],
                'required' => false
            ])

        ->add('star', RadioType::class,
            [
                'label_attr' => ['class' => 'sr-only'],
                'required' => false
            ])

我打算为8种选择提供8种不同的RadioTypes。确定选择哪种RadioType的最佳方法是什么。我目前的实现是每个都有一个if声明,但这似乎是一个糟糕的解决方案。

if ($form->getData()['info'] == true) {
            //do stuff
        }
        if ($form->getData()['star'] == true) {
            //do stuff
        }
php symfony symfony-forms
2个回答
2
投票

According to the documentation,你通常不应该直接使用RadioType。使用ChoiceType object可以使您遵循预期的HTML标准,这意味着您使用相同的名称,但每个元素使用不同的值。通过这种方式,浏览器将像单选按钮一样自动将用户限制为单一选择。

<?php
$builder->add('yourCategory', ChoiceType::class, [
    'choices' => [
        'Info' => 'info',
        'Star' => 'star',
        'Some other label' => 'other',
    ],
    // attributes for label elements
    'label_attr' => ['class' => 'sr-only'],
    // attributes for input elements
    'choice_attr' => [
        'Info' => ['class' => 'fa fa-info'],
        'Star' => ['class' => 'fa fa-star'],
        'Some other label' => ['class' => 'whatever'],
     ],
    // setting these options results in radio buttons
    // being generated, instead of a select element
    'expanded' => true,
    'multiple' => false,
]);

然后在你的控制器中:

switch($form->getData()['yourCategory']) {
    case 'info':
        // do stuff
        break;
    case 'star':
        // do stuff
        break;
    case 'other':
        // do stuff
        break;
}

0
投票

所以我最终能够手动更改每个选项的标签

{# Manually set the label for each choice in the form, so only an icon is shown #}
        <label for="{{ form.choices.children[0].vars.id}}" class="mt-2">
            <span class="fa-stack fa-2x type-icon" id="info-type">
                <span class="fas fa-circle fa-stack-2x circle"></span>
                <span class="info fas fa-info fa-stack-1x"></span>
            </span>
         </label>
© www.soinside.com 2019 - 2024. All rights reserved.