php @Assert\NotBlank验证在symfony 4的嵌入式表单中不起作用

lndjwyie  于 2023-08-02  发布在  PHP
关注(0)|答案(2)|浏览(130)

我有一个名为BlockType的表单,其中有一个名为BlockHeroStaticImageType的嵌入表单。嵌入表单BlockHeroStaticImageType中名为'title'的字段包含验证注解@Assert\NotBlank(),如下图所示(参见下面的BlockHeroStaticImage Entity)。当我在表单中将title保留为空并尝试保存表单时,不会触发表单验证。验证应该失败,但事实并非如此。我在控制器中检查了$form->isValid(),它返回true,尽管标题是emtpy。我错过了什么?请帮帮我

  • 块类型表单 *
class BlockType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('content', TextareaType::class, [
                'required' => false,
                'attr' => [
                    'class' => 'ckeditor',
                    'data-field' => 'content'
                ]
            ])
            ->add('blockHeroStaticImages', CollectionType::class, [
                'entry_type' => BlockHeroStaticImageType::class,
                'entry_options' => ['label' => false],
                'label' => 'Hero Static Image',
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'help' => '<a data-collection="add" class="btn btn-info btn-sm" href="#">Add Hero Static Image</a>',
                'help_html' => true,
                'attr' => [
                    'data-field' => 'blockHeroStaticImages'
                ]
            ]);

    }

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

字符串

  • 块实体 *
/**
 * @ORM\Entity(repositoryClass="App\Repository\BlockRepository")
 */
class Block
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $content;

   /**
    * @ORM\OneToMany(targetEntity="App\Entity\Block\BlockHeroStaticImage", mappedBy="block", orphanRemoval=true, cascade={"persist"})
    */
    private $blockHeroStaticImages;

    public function __construct()
    {
        $this->blockHeroStaticImages = new ArrayCollection();

    }

    ...

    /**
     * @return Collection|BlockHeroStaticImage[]
     */
    public function getBlockHeroStaticImages(): Collection
    {
        return $this->blockHeroStaticImages;
    }

    public function addBlockHeroStaticImage(BlockHeroStaticImage $blockHeroStaticImage): self
    {
        if (!$this->blockHeroStaticImages->contains($blockHeroStaticImage)) {
            $this->blockHeroStaticImages[] = $blockHeroStaticImage;
            $blockHeroStaticImage->setBlock($this);
        }

        return $this;
    }

    public function removeBlockHeroStaticImage(BlockHeroStaticImage $blockHeroStaticImage): self
    {
        if ($this->blockHeroStaticImages->contains($blockHeroStaticImage)) {
            $this->blockHeroStaticImages->removeElement($blockHeroStaticImage);
            // set the owning side to null (unless already changed)
            if ($blockHeroStaticImage->getBlock() === $this) {
                $blockHeroStaticImage->setBlock(null);
            }
        }

        return $this;
    }
}

  • BlockHeroStaticImageType表单 *
class BlockHeroStaticImageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class, [
                'required' => false
            ]);
    }

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

  • BlockHeroStaticImage实体 *
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\Block\BlockHeroStaticImageRepository")
 */
class BlockHeroStaticImage
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     */
    private $title;
    
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Block", inversedBy="blockHeroStaticImages")
     * @ORM\JoinColumn(nullable=false)
     */
    private $block;

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

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

}

zd287kbt

zd287kbt1#

通过查看documentation,您应该在发送表单之前调用$validator->validate($object)
另外,不确定它现在是否工作,但文档中提供的用于添加NotBlank约束的语法是@Assert\NotBlank,没有括号。

toe95027

toe950272#

在Symfony 6中遇到了同样的问题。通过将#[Assert\Valid]添加到父/所有者实体中的OneToMany属性来修复。
此约束记录在此处:https://symfony.com/doc/current/reference/constraints/Valid.html
此约束用于对作为属性嵌入到要验证的对象上的对象启用验证。这使您可以验证对象及其关联的所有子对象。
在OP的情况下,也使用注解,修复将是:

/**
  * @ORM\OneToMany(targetEntity="App\Entity\Block\BlockHeroStaticImage", mappedBy="block", orphanRemoval=true, cascade={"persist"})
  * @Assert\Valid()
  */
private $blockHeroStaticImages;

字符串

相关问题