Symfony2验证OneToMany ImageCollection的Image实体

时间:2013-07-20 18:35:23

标签: php image validation symfony doctrine-orm

我在验证新上传文件时遇到问题。

我有我的产品实体:

// 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 - 不是。

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

大师能帮助我吗?

1 个答案:

答案 0 :(得分:2)

要验证收集,您可以使用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