Symfony 5 控制器不会验证错误

Symfony 5 controller won't validate errors

我正在尝试将使用 Typescript + Express + Firebase 制作的项目的某些部分迁移到 Symfony 5 和 MySQL。但我不明白为什么 ValidatorInterface 不起作用。

当我提交包含意外字符的表单(即:具有 3 个字符的密码)时,尽管 validation constraints assigned in the User entity. The only constraint validation that actually works despites it does not show any form errors, is the UniqueEntity.

这是我的控制器的样子:

    /**
     * GET: Display form
     * POST: Creates a user
     * 
     * @Route("/users/crear", name="create_user", methods={"GET", "POST"})
     */
    public function create_user(Request $request, EntityManagerInterface $entityManager, ValidatorInterface $validator)
    {
        $user = new User();

        // Form
        if ($request->isMethod('GET')) {
            $form = $this->createForm(CrearUserType::class, $user);
            return $this->render('user/create.html.twig', [
                'form' => $form->createView(),
                'errors' => []
            ]);
        }

        // Form submit
        $data = $request->request->get('create_user');
        $errors = [];

        $user->setName($data['name']);
        $user->setEmail($data['email']);
        $user->setPassword($data['password']);
        $user->setCreatedAt(new \DateTime());
        $user->setUpdatedAt(new \DateTime());

        $form = $this->createForm(CrearUserType::class, $user);

        // Entity validation
        $errors = $validator->validate($user);        

        if (count($errors) > 0) { // This is always 0
            $user->setPassword('');
            return $this->render('user/create.html.twig', [
                'form' => $form->createView(),
                'user' => $user,
                'errors' => $errors
            ]);
        }

        try {
            $user->setPassword(password_hash($user->getPassword(), PASSWORD_BCRYPT));
            $entityManager->persist($user);
            $entityManager->flush();
            $this->addFlash(
                'success', 
                'User '.$user->getName().' has been saved.'
            );
            return $this->redirectToRoute('users');
        } catch(\Exception $exception) {
            $user->setPassword('');
            $this->addFlash(
                'error', 
                'Server error: ' . $exception->getMessage()
            );
            return $this->render('user/create.html.twig', [
                'form' => $form->createView(),
                'user' => $user,
                'errors' => $errors
            ]);
        }
    }

这是我的实体:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @UniqueEntity("email")
 */
class User
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank(message="Name is mandatory")
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255, unique=true)
     * @Assert\NotBlank(message="Email is mandatory")
     * @Assert\Email(
     *  message="Invalid email address"
     * )
     */
    private $email;
    /**
     * @ORM\Column(type="string", length=60)
     * @Assert\NotBlank(message="Password is mandatory")
     * @Assert\GreaterThanOrEqual(
     *  value=6,
     *  message="The password has to be at least 6 chars long"
     * )
     */
    private $password;

    /**
     * @ORM\Column(type="date")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="date")
     */
    private $updatedAt;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(?string $password): self
    {
        $this->password = $password;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(\DateTimeInterface $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }
}

那么,这里有什么问题的线索吗?

我不确定我的回答,因为我从不使用 ValidatorInterface 处理请求。我使用controller提供的handlerequest方法

您创建了表单

 $form = $this->createForm(CrearUserType::class, $user);

但是你忘了处理请求

 $form->handleRequest($request);

因此您的表单不验证请求转发的数据。尝试在 $form 创建之后添加这一行。然后,您可以使用

测试用户实体是否有效
if ($form->isValid()) {
 //no errors
}
//error exists