【问题标题】:Different constraint while editing and creating new record编辑和创建新记录时的不同约束
【发布时间】:2020-11-10 02:58:22
【问题描述】:

所以基本上我正在尝试对图像属性添加约束。但问题是,当我创建一个新帖子并上传图片时,file 属性已被填充。当我编辑帖子时,它填充了path 属性,而不是file。如何解决此验证问题,以便始终需要 pathfile?目前,如果我编辑帖子,我会收到验证错误,因为file 将为空,path 不会为空

ArticleImage.php

/**
 * @Assert\Image(
 *     maxSize="1024k",
 *     mimeTypes={"image/jpeg", "image/jpg", "image/png"}
 * )
 * @Assert\NotNull()
 */
protected $file;

/**
 * @Assert\NotNull()
 */
protected $path;

Article.php 实体有这个属性:

/**
 * @ORM\OneToOne(targetEntity="Article", mappedBy="owner")
 */
private ?ImageInterface $image = null;

【问题讨论】:

    标签: symfony doctrine constraints


    【解决方案1】:

    您可以创建一个新的constraint for the class,例如文件,它将检查您的字段。你可以通过你的类扩展 symfony Image 约束和验证器,在验证器中你可以做这样的事情

    public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof File) {
            throw new UnexpectedTypeException($constraint, File::class);
        }
    
        if (!$value instanceof SomeClass) {
            return;
        }
    
        if (!$value->getPath() && !$value->getFile()) {
            $this->context->buildViolation('empty file')
                ->atPath('file')
                ->addViolation();
    
            return;
        }
    
        if ($value->getFile()) {
            // will validate your image
            parent::validate($value->getFile(), $constraint);
    
            return;
        }
    }
    

    或者你可以使用validation groups

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 2014-10-22
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      • 2017-05-23
      • 1970-01-01
      相关资源
      最近更新 更多