Allow to add a new value in a choice Field Type

后端 未结 3 1625
名媛妹妹
名媛妹妹 2021-02-05 15:20

I use Form Component and have a choice Field Type on a form which is rendered to a select field. On a client-side I use select2 plugin which initializes the select with the sett

3条回答
  •  轮回少年
    2021-02-05 15:39

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

提交回复
热议问题