如何解决Select2 选定的选项在 Symfony 5
我的表单中有一个 select2 choicetype 字段,它使用 ajax 从 API 中检索选项。它是 symfony 形式的一部分。字段配置如下:
->add('places',ChoiceType::class,[
'multiple' => true,'label' => $this->t->trans('places'),'attr' => ['class' => 'select2-multiple'],'label_attr' => ['class' => 'control-label'],'help' => $this->t->trans('create_new_announcement_places_help'),'constraints' => [new NotBlank(['message' => 'field_empty'])],'required' => true,])
启用 select2 属性的 javascript 如下所示,并且可以正常工作。
$("#create_places").select2({
ajax: {
url: GLOBALS.publicApi + "/geocode/city?token=" + GLOBALS.clientToken,dataType: 'json'
// Additional AJAX parameters go here; see the end of this chapter for the full code of this example
},minimumInputLength: 3
});
在服务器端,表单是这样处理的:
public function create($projectId,Request $request)
{
$project = $this->getProject($projectId);
$createForm = $this->createForm(CreateType::class);
$createForm->handleRequest($request);
if ($createForm->isSubmitted() && $createForm->isValid()) {
$this->handleCreateFormRequest($createForm,$projectId);
} elseif ($createForm->isSubmitted() && !$createForm->isValid()) {
dump($createForm->getData());
dump($_POST);
$this->addFlash('danger',$this->trans('create_announcement_wizard_error'));
}
return $this->render('client/announcements/create.html.twig',['createForm' => $createForm->createView(),'project' => $project]);
}
然而,$createForm->getData() 确实具有所有其他字段值,但不是由用户选择的 select2 选项。但是在本机 $_POST 数组中,选择的选项确实存在。 当 select2 字段使用静态选项而不是远程数据时,它运行良好。 此外,symfony 表单验证失败,这是本例中的逻辑行为。
Select2 版本:4.0.13 Symfony 版本:5
有谁知道如何解决这个问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。