Allow the addition of new values to a ChoiceType Field
Asked Answered
W

3

16

I use Form Component and have a ChoiceType field on the form which is rendered to a select field. On the client-side I use select2 plugin which initializes a select with tags: true allowing the addition of new values to it.
But if I add a new value then a validation on the server fails with an error

This value is not valid.

because the new value isn't in the choice list.

Is there a way to allow the addition of new values to a ChoiceType field?

Wolford answered 17/9, 2015 at 10:24 Comment(0)
W
27

The problem is in a choice transformer, which erases values that don't exist in a choice list.
The workaround with disabling the transformer helped me:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('choiceField', 'choice', ['choices' => $someList]);

    // more fields...

    $builder->get('choiceField')->resetViewTransformers();
}
Wolford answered 17/9, 2015 at 11:36 Comment(1)
Guys does this suggestion worked for you? I tried to implement it in a SonataAdmin project but seems doing nothing... $formMapper->add('serviceType', ChoiceType::class)->get('serviceType')->resetViewTransformers()Greenman
C
9

Here's an example code in case someone needs this for EntityType instead of the ChoiceType. Add this to your FormType:

use AppBundle\Entity\Category;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
    $data = $event->getData();

    if (!$data) {
        return;
    }

    $categoryId = $data['category'];

    // Do nothing if the category with the given ID exists
    if ($this->em->getRepository(Category::class)->find($categoryId)) {
        return;
    }

    // Create the new category
    $category = new Category();
    $category->setName($categoryId);
    $this->em->persist($category);
    $this->em->flush();

    $data['category'] = $category->getId();
    $event->setData($data);
});
Catch answered 27/6, 2016 at 12:21 Comment(1)
Working on Symfony4. ThanksKnown
V
3

No, there is not.

You should implement this manually by either:

  • using the select2 events to create the new choice via ajax
  • catching the posted options before validating the form, and add it to the options list
Vulpecula answered 17/9, 2015 at 10:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.