Allow to add a new value in a choice Field Type

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();
}

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

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