为什么 symfony 断言在编辑页面上没有验证属性时不起作用?

Why symfony assert doesnt work with novalidation attribute on Edit Page?

在我的表单中,我使用的是 novalidate 属性,如下所示:

{{ form_start(form, {'attr': {novalidate: 'novalidate'}}) }}                

禁用HTML5 浏览器验证。 所以出现 Symfony 断言错误。 在 new.html.twig 页面上它工作得很好! novalidate 属性禁用 html5 验证并出现断言错误。

但是,当我在 edit.html.twig 上使用 novalidate 属性并将 username 字段留空(我没有在表单上填写它)时,@Assert\NotBlank() 不起作用。我得到这个错误

Expected argument of type "string", "null" given at property path "username".

为什么 symfony 断言在 new 页面上工作,但在 edit 页面上不起作用? 顺便说一句,我没有使用任何验证组。

这是我的用户实体的代码(没有 getter 和 setter):

class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Email()
     * @Assert\NotBlank()
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 8, max = 30,
     *      minMessage = "Your password must be between 6 and 30 characters.")     
     */
    private $password;
    
    /**
     * @ORM\Column(type="json", nullable=true )
     */
    private $roles = [];

下面是表格的代码:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', EmailType::class )
            ->add('username', TextType::class)
            ->add('password',PasswordType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

new.html.twig和edit.html.twig的代码相同:

{{ form_start(form, {'attr': {novalidate: 'novalidate'}}) }}    

    {{ form_widget(form.email, {'attr': {'class': 'form-control',placeholder: 'Email Adress'} }) }}     
    {{form_errors(form.email)}}

    {{ form_widget(form.username, {'attr': {'class': 'form-control',placeholder: 'Username'} }) }}
    {{form_errors(form.username)}}

    {{ form_widget(form.password, {'attr': {'class': 'form-control'} }) }}
    {{form_errors(form.password)}}

    <button class="btn btn-success">Submit</button>
{{ form_rest(form) }}
{{ form_end(form) }}

控制器代码:

/**
 * @Route("/new", name="user_new", methods={"GET","POST"})
 */
public function new(Request $request): Response
{
    $user = new User();
    $form = $this->createForm(UserType::class, $user);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($user);
        $entityManager->flush();

        return $this->redirectToRoute('user_index');
    }

    return $this->render('user/new.html.twig', [
        'user' => $user,
        'form' => $form->createView(),
    ]);
}


/**
 * @Route("/{id}/edit", name="user_edit", methods={"GET","POST"})
 */
public function edit(Request $request, User $user): Response
{
    $form = $this->createForm(UserType::class, $user);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $this->getDoctrine()->getManager()->flush();

        return $this->redirectToRoute('user_index');
    }

    return $this->render('user/edit.html.twig', [
        'user' => $user,
        'form' => $form->createView(),
    ]);
}

我的吸气剂和吸气剂:

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

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

    return $this;
}
public function getUsername(): ?string
{
    return $this->username;
}

public function setUsername(string $username): self
{
    $this->username = $username;

    return $this;
}


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

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

    return $this;
}

我认为你应该在所有 setter 的字符串类型中添加 ? 符号。

比如改成发件人 setUsername(string $username): self setUsername(?string $username): self

这应该可以解决编辑页面上的断言问题。