我使用表单组件
,在表单上有一个ChoiceType字段,被呈现为选择字段。
客户端使用select2插件,它使用tags: true
初始化选择器,允许向其中添加新值。
但是,如果我添加新值,那么服务器端的验证将会失败并出现以下错误:
此值无效。
因为新值不在可选列表中。
是否有一种方法可以允许向ChoiceType字段
添加新值?
我使用表单组件
,在表单上有一个ChoiceType字段,被呈现为选择字段。
客户端使用select2插件,它使用tags: true
初始化选择器,允许向其中添加新值。
但是,如果我添加新值,那么服务器端的验证将会失败并出现以下错误:
此值无效。
因为新值不在可选列表中。
是否有一种方法可以允许向ChoiceType字段
添加新值?
问题出在选择转换器上,它会删除不在选项列表中的值。
通过禁用转换器的解决方法对我很有帮助:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('choiceField', 'choice', ['choices' => $someList]);
// more fields...
$builder->get('choiceField')->resetViewTransformers();
}
以下是一个示例代码,如果有人需要使用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);
});
不,没有。
您可以通过以下两种方式手动实现: