允许向ChoiceType字段添加新值

16

我使用表单组件,在表单上有一个ChoiceType字段,被呈现为选择字段。 客户端使用select2插件,它使用tags: true初始化选择器,允许向其中添加新值。
但是,如果我添加新值,那么服务器端的验证将会失败并出现以下错误:

此值无效。

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

是否有一种方法可以允许向ChoiceType字段添加新值?

3个回答

26

问题出在选择转换器上,它会删除不在选项列表中的值。
通过禁用转换器的解决方法对我很有帮助:

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() - rollsappletree

9

以下是一个示例代码,如果有人需要使用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);
});

2
正在使用Symfony4进行开发。谢谢。 - kamui

3

不,没有。

您可以通过以下两种方式手动实现:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接