【问题标题】:Allow to add a new value in a choice Field Type允许在选择字段类型中添加新值
【发布时间】:2015-12-14 04:29:46
【问题描述】:

我使用表单组件并在呈现给选择字段的表单上有一个choice Field Type。 在客户端,我使用select2 plugin,它使用tags: true 设置初始化选择,允许在其中添加新值。 但是如果我添加一个新值,那么服务器上的验证将失败并出现错误

此值无效。

因为新值不在选择列表中。

有没有办法允许添加新值来选择字段类型?

【问题讨论】:

    标签: symfony jquery-select2 symfony2-forms


    【解决方案1】:

    问题出在选择转换器中,它会删除选择列表中不存在的值。
    The workaround with disabling the transformer 帮助了我:

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

    【讨论】:

    • 伙计们,这个建议对你有用吗?我试图在 SonataAdmin 项目中实现它,但似乎什么也没做... $formMapper->add('serviceType', ChoiceType::class)->get('serviceType')->resetViewTransformers()
    【解决方案2】:

    这里有一个示例代码,以防有人需要它作为 EntityType 而不是 ChoiceType。将此添加到您的 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);
    });
    

    【讨论】:

    • 在 Symfony4 上工作。谢谢
    【解决方案3】:

    不,没有。

    您应该通过以下任一方式手动实现:

    • 使用 select2 事件通过 ajax 创建新选择
    • 在验证表单之前捕获已发布的选项,并将其添加到选项列表中

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多