Search code examples
phpsymfonysymfony-formssymfony4

Symfony 4 - isValid always returns false


I'm trying to validate my form by using $form->isValid(). But even if my form is correct it returns false. I already tried to dump my errors with $form->getErrors(true) but then my request times out.

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);
        }

    }
}

My 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 to POST

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

Thanks in advance for your help!


Solution

  • I fixed it by adding 'multiple' => true to my heroes entry, so the form knows it's an array and by disable CSRF protection ('csrf_protection' => false as parameter in $resolver).