Alexey Kosov
Alexey Kosov

Reputation: 3150

Form entity: add an extra option

I use a Symfony form for filtering a set of data. Say, there's a "User" dropdown filtering a table of log records (each record can be linked with a user, but can be not linked).

In other words, LogRecord <- many-to-one nullable -> User

The catch is that I want it to support 2 options in the dropdown list: All Users (disables filtering by this field) and "No User" which should filter records having the field = NULL. But I have no idea how to learn the form to distinguish those cases, not breaking the form validation process. Any ideas?

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->setMethod('GET');

    $builder
        ->add('user', EntityType::class, array(
            'class' => 'AppBundle:User',
            'choice_label' => 'name',
            'placeholder' => 'All',
            'query_builder' => function (UserRepository $repo) {
                return $repo->findForOptionsQueryBuilder();
            },
            'label' => 'User',
            'required' => false,
        ));
}

Current dropdown:

Desired dropdown:

Upvotes: 5

Views: 1868

Answers (1)

yceruto
yceruto

Reputation: 9585

One idea could be using ChoiceType instead. Something like this:

// all your users
$choices = $repo->findForOptionsQueryBuilder()->getQuery()->getResult();

// add None option
$choices = array_merge(['None' => 0], $choices);

$builder->add('user', ChoiceType::class, [
    'choices' => $choices,
    'placeholder' => 'All', // add All option to beginning
    'required' => false,
    'choice_label' => function ($value, $key) {
        return $value ?: $key;
    },
]);

This should render the follows HTML input:

<select id="form_user" name="form[user]">
    <option value="">All</option>
    <option value="0">None</option>
    <option value="1">User A</option>
    <option value="2">User B</option>
    <option value="3">User C</option>
</select>

And, on submitting event:

  • If option "All" is selected then $form->get('user')->getData() is equal to null
  • If option "None" is selected then $form->get('user')->getData() is equal to 0
  • If option "User A" is selected then $form->get('user')->getData() is an instance of User

Thus you can distinguish these cases without breaking the form validation process.

Upvotes: 5

Related Questions