Ilia Shakitko
Ilia Shakitko

Reputation: 1457

Symfony2 validation of OneToMany ArrayCollection of Image entities

I am facing a problem with validation of new uploaded file.

I have my Product entity:

// 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;
}

Image entity is a very simple, with name, size, mimetype.

And I have working on some custom upload listener, so I am not using form and form->isValid. I validate like this:

...
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);

And I've got an error:

{"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":[]}

If let say I do NotNull annotation Assert on enother field (like name) - it works, I can get errors. But with ArrayCollection - is not.

I am doing something wrong and can't find info in the internet.

Could the gurus help me out?

Upvotes: 0

Views: 2254

Answers (1)

Alexey B.
Alexey B.

Reputation: 12033

To validate collection you can use All and Valid validators.

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

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

Upvotes: 2

Related Questions