首页 > 解决方案 > 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
}

在此先感谢您的帮助!

标签: phpsymfonysymfony-formssymfony4

解决方案


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


推荐阅读