d1596
d1596

Reputation: 1307

Determine which RadioType form was selected in contorller

I have a form that has multiple RadioTypes to represent a category for a Announcement entity.

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

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

I plan on having 8 different RadioTypes for 8 choices. What is the best way to determine which RadioType was selected. My current implementation is to have an if statement for each but that seems like a poor solution.

if ($form->getData()['info'] == true) {
            //do stuff
        }
        if ($form->getData()['star'] == true) {
            //do stuff
        }

Upvotes: 1

Views: 266

Answers (2)

d1596
d1596

Reputation: 1307

So I ended up being able to change each individual choice's label manually

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

Upvotes: 0

miken32
miken32

Reputation: 42714

According to the documentation, you shouldn't typically be using RadioType directly. Using the ChoiceType object allows you to follow expected HTML standards, meaning you use the same name but a different value for each element. This way the browser will, as has always been the case for radio buttons, automatically restrict the user to a single choice.

<?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,
]);

Then in your controller:

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

Upvotes: 3

Related Questions