Symfony 4-isValid始终返回false

时间:2018-07-06 17:32:10

标签: php symfony symfony-forms symfony4

我正在尝试使用$form->isValid()来验证我的表单。但是,即使我的表格是正确的,它也会返回false。我已经尝试用$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);
        }

    }
}

我的Form.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

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

在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我相信您可能要遵循https://symfony.com/doc/4.1/forms.html#handling-form-submissions

中的文档中所述的做法。

根据您的情况将文章示例分为多个步骤:

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