繁体   English   中英

Symfony2验证OneToMany ImageCollection的Image实体

[英]Symfony2 validation of OneToMany ArrayCollection of Image entities

我正面临验证新上传文件的问题。

我有我的产品实体:

// src/Acme/DemoBundle/Entity/Product
...
/**
 * @ORM\OneToMany(targetEntity="Image", mappedBy="product", cascade={"persist"})
 * @Assert\Image(
 *     minWidth = 10,
 *     maxWidth = 20,
 *     minHeight = 10,
 *     maxHeight = 20
 * )
 */
protected $images;
...
public function __construct()
{
    $this->images= new \Doctrine\Common\Collections\ArrayCollection();
}
public function getImages(){
    return $this->images;
}

public function setImages($images){
    $this->images = $images;

    return $this;
}

图像实体非常简单,具有名称,大小,mimetype。

我已经开发了一些自定义上传监听器,所以我没有使用form和form-> isValid。 我这样验证:

...
public function onUpload(PostPersistEvent $event)
{
        $em= $this->doctrine->getManager();
        $product = $this->doctrine->getRepository('Acme\DemoBundle\Entity\Product')->findOneById($customId);

        $image = new Image();
        $image->setProduct($product)
               ->setName($uploadInfo->name)
               ->setStoredName($uploadInfo->storedName)
               ->setUuid($uploadInfo->uuid)
               ->setSize($uploadInfo->size)
               ->setMimeType($uploadInfo->mimeType);

        $validator = Validation::createValidatorBuilder()
        ->enableAnnotationMapping()
        ->getValidator();

        $a = $product->getImages();
        $a->add($image);
        $product->setImages($a);

        $errors = $validator->validate($product);

我有一个错误:

{"message":"Expected argument of type string, object given","class":"Symfony\\Component\\Validator\\Exception\\UnexpectedTypeException","trace":[{"namespace":"","short_class":"","class":"","type":"","function":"","file":".../vendor\/symfony\/symfony\/src\/Symfony\/Component\/Validator\/Constraints\/FileValidator.php","line":98,"args":[]}

如果让我说NotNull注释在另一个字段上断言(比如名字) - 它可以工作,我可以得到错误。 但是使用ArrayCollection - 不是。

我做错了什么,无法在互联网上找到信息。

大师可以帮帮我吗?

要验证集合,您可以使用AllValid验证器。

Acme\DemoBundle\Entity\Product:
    properties:
        images:
            - Valid: ~
            - All:
                - NotNull: ~

Acme\DemoBundle\Entity\Image:
    properties:
        file:
            - Image:
                minWidth: 200
                maxWidth: 400
                minHeight: 200
                maxHeight: 400

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM