php - Symfony 4 - isValid 总是返回 false
问题描述
我正在尝试使用$form->isValid()
. 但即使我的表格是正确的,它也会返回错误。我已经尝试转储我的错误,$form->getErrors(true)
但后来我的请求超时。
我的 CreateController.php:
class CreateController extends Controller
{
/**
* @Method({"POST"})
* @Route("/api/v1/matches", name="api_v1_matches_create")
*/
public function index(Request $request, EntityManagerInterface $em): JsonResponse
{
$data = json_decode($request->getContent(), true);
$match = new Match();
$form = $this->createForm(MatchFormType::class, $match);
$form->submit($data);
if ($form->isValid()) {
$em->persist($match);
$em->flush();
return new JsonResponse(null, 201);
} else {
return new JsonResponse(null, 400);
}
}
}
我的表格.php
class MatchFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add(
'heroes',
EntityType::class,
[
'class' => Hero::class,
]
)
->add(
'season',
EntityType::class,
[
'class' => Season::class,
]
)
->add(
'map',
EntityType::class,
[
'class' => Map::class,
]
);
}
public function getName(): string
{
return 'match';
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Match::class,
]);
}
}
JSON 到 POST
{
"map": 1,
"heroes": [
1,
2
],
"season": 1
}
在此先感谢您的帮助!
解决方案
我通过添加到我的英雄条目来修复它'multiple' => true
,因此表单知道它是一个数组并禁用 CSRF 保护('csrf_protection' => false
作为 $resolver 中的参数)。
推荐阅读
- kubernetes - Kubernetes 报告“pod 没有触发扩展(如果添加了新节点,它将不适合)”,即使它会?
- delphi - 让 Delphi 使用新版本的 Microsoft Access 读取数据库
- kubernetes - 使用 nginx-ingress 在 gke 中进行 gzip
- python - Pandas GroupBy 后缺少列(不是 GroupBy 列)
- javascript - Javascript 正则表达式 - 捕获前面有另一个字符串的字符串
- django - 获取与使用 ModelMultipleChoiceField 时添加的对象相关的所有对象
- docker - 使用 docker 的多台机器的 Redis 集群
- twilio-flex - 如何解决“警告:无效的 DOM 属性 `fill-rule`。您的意思是 `fillRule`?” 在 Twilio Flex 上
- vim - vim 命令在以模式开头的文件中所有行的末尾添加分号
- processing - 平移后按定义的量旋转每个圆 - 处理