我在验证新上传的文件时遇到了一个问题。
我有我的产品实体:
// 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注释Assert——它有效,我可能会得到错误。但对于ArrayCollection,情况并非如此。
我做错了什么,在网上找不到信息。
大师们能帮我吗?
要验证集合,可以使用All和Valid验证器。
Acme'DemoBundle'Entity'Product:
properties:
images:
- Valid: ~
- All:
- NotNull: ~
Acme'DemoBundle'Entity'Image:
properties:
file:
- Image:
minWidth: 200
maxWidth: 400
minHeight: 200
maxHeight: 400