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