允许在选择字段类型中添加新值

时间:2015-09-17 10:24:21

标签: symfony jquery-select2 symfony2-forms

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

  

此值无效。

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

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

3 个答案:

答案 0 :(得分:17)

问题在于选择变换器,它会擦除​​选择列表中不存在的值 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();
}

答案 1 :(得分:4)

这是一个示例代码,以防有人需要为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 :(得分:3)

不,没有。

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

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