Symfony 4 - isValid总是返回false



我正在尝试使用$form->isValid()来验证我的表单。但即使我的表单是正确的,它也返回 false。我已经尝试用$form->getErrors(true)转储我的错误,但随后我的请求超时了。

My 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,
]);
}
}

待发布

{
"map": 1,
"heroes": [
1,
2
],
"season": 1
}

提前感谢您的帮助!

我通过在英雄条目中添加'multiple' => true来修复它,因此表单知道它是一个数组并禁用 CSRF 保护('csrf_protection' => false$resolver 中的参数(。

我相信您可能希望遵循此处文档中描述的做法 https://symfony.com/doc/4.1/forms.html#handling-form-submissions

将文章示例划分为您可能需要的步骤:

  1. 创建新的表单对象
  2. 处理 http 请求
  3. 检查表单是否正在提交且有效
  4. 如果满足先前的条件,则获取表单数据并将其刷新到数据库

最新更新