Allow adding a new value to the Field Type field

I use the form component and the field type of the field in the form that appears in the selection box. On the client side, I use select2 plugin , which initializes the selection using the tags: true parameter, which allows you to add a new value to it. But if I add a new value, then the check on the server will fail

This value is invalid.

because the new value is not in the select list.

Is there a way to allow the addition of a new value to the choice of field type?

+6
source share
3 answers

The problem is choosing a transformer that erases values ​​that do not exist in the selection list.
The workaround with turning off the transformer helped me:

 public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('choiceField', 'choice', ['choices' => $someList]); // more fields... $builder->get('choiceField')->resetViewTransformers(); } 
+13
source

Here is a sample code if someone needs it for EntityType instead of ChoiceType. Add this to your FormType form:

 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); }); 
+3
source

No no.

You must implement this manually:

  • using select2 events to create a new selection via ajax
  • intercept published parameters before validating the form and add them to the list of options
+1
source

All Articles