Symfony 7:在属性路径“Title”处给出的预期参数类型为“string”,“null”

问题描述 投票:0回答:1

这主要是一个理解问题,因为我找到了解决方案,但我不太确信。

我有两种方法,

new
edit
,如下所示:


    #[Route('film/new', name: 'app_film_new', methods: ['GET','POST'])]
    public function new(Request $request, EntityManagerInterface $em): Response
    {

        $form = $this->createForm(FilmType::class,null,  ['method' => 'POST']);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $film = new film();
            $film = $form->getData();
            $em->persist($film);
            $em->flush();
            
            $this->addFlash('success', 'Le film a bien été créé');
            return $this->redirectToRoute('app_show_film', ['id' => $film->getId()]);
        } 

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


    #[Route('film/{id}/edit', name: 'app_film_edit', methods: ['GET', 'POST'])]
    public function update(Film $film, Request $request, EntityManagerInterface $em): Response
    {
        $form = $this->createForm(FilmType::class, $film, ['method' => 'POST']);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $film = $form->getData();
            
            $em->flush();
            $this->addFlash('success', 'Le film a bien été modifié');
            return $this->redirectToRoute('app_show_film', ['id' => $film->getId()]);
            }
        }

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

在我的 FilmEntity 中,我有关于 Title 属性的信息,例如:


    #[Assert\NotBlank(message:"Le titre ne peut pas être vide.")]
    #[ORM\Column(length: 255, nullable:false)]
    private ?string $titre = null;

当我使用新表单进行测试时,如果我在标题字段中放置任何内容(并删除该字段的“必需”属性”),则会出现任何问题:我可以看到标题字段下方有错误的表单,如下所示约束问它。

但是当我对编辑表单执行相同的操作时,在这种情况下,我会出现错误:

属性路径“titre”处给出的预期参数类型为“string”、“null”。

我已经通过添加“?”解决了这个问题在设置器中的“字符串”之前。

    public function setTitre(?string $titre): static
    {
        $this->titre = $titre;

        return $this;
    }

但我不明白为什么只有在一种情况下才会出现这种行为,以及为什么在设置器之前不读取约束。

有人给我解释一下吗? 谢谢。

symfony constraints
1个回答
0
投票

您遇到的行为是,在编辑情况下的表单提交期间不遵守约束,但在新情况下工作正常,这可能是由于 Symfony 处理表单数据绑定的方式所致。

在新的情况下,当您创建一个新的 Film 对象时,Symfony 的表单系统会将该对象的所有属性初始化为其默认值,这在 PHP 中通常意味着可为 null 的属性(如

$titre
)为 null。当您提交表单时,Symfony 会将表单数据绑定到对象,并且由于表单字段不为空,因此它将
titre
属性设置为提交的值。如果该值不满足约束,Symfony 会正确显示错误。

但是,在编辑情况下,Symfony 从数据库中检索现有的 Film 对象。如果该对象的

titre
属性在数据库中为 null,并且您的表单字段未标记为必填,则 Symfony 在提交的表单中看不到
titre
字段的任何数据,因此不会设置任何事物的
titre
属性。因此,当 Symfony 尝试验证对象时,它会遇到
titre
的空值,这违反了期望字符串的约束。

通过在实体中使

titre
属性可为空并相应地调整 setter,您实际上是在告诉 Symfony
titre
属性为空是可以接受的,从而解决了验证错误。

关于为什么在 setter 之前不读取约束,Symfony 的表单系统首先将数据设置到对象上,然后验证它。此顺序确保在验证期间考虑设置器应用的任何转换或操作。虽然这种行为在某些情况下可能看起来违反直觉,但它通常与 Symfony 处理表单数据的方式一致。

© www.soinside.com 2019 - 2024. All rights reserved.