Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a list of images to an entity with VichUploaderBundle

Tags:

php

symfony

I have an entity "Comment", and a "Comment" could have one or more images associated. How do i achieve that.

Now i have this(for just one image):

/**
 * @Assert\File(
 *     maxSize="1M",
 *     mimeTypes={"image/png", "image/jpeg"}
 * )
 * @Vich\UploadableField(mapping="comment_mapping", fileNameProperty="imageName")
 *
 * @var File $image
 */
protected $image;

Thanks in advance

like image 414
Oriam Avatar asked May 24 '13 00:05

Oriam


1 Answers

You have to create a ManyToOne relationship between your Comment and Image entities.

Read more on associations with doctrine 2 here.

Comment

/**
 * @ORM\ManyToOne(targetEntity="Image", inversedBy="comment")
 */
protected $images;

public function __construct()
{
     $this->images = new ArrayCollection();
}

public function getImages()
{
    return $this->images;
} 

public function addImage(ImageInterface $image)
{
    if (!$this->images->contains($image)) {
        $this->images->add($image);
    }

    return $this;
}

public function removeImage(ImageInterface $image)
{
    $this->images->remove($image);

    return $this;
}

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

// ...

Image

protected $comment;

public function getComment()
{
   return $this->comment;
}

public function setComment(CommentInterface $comment)
{
    $this->comment = $comment;

    return $this;
}

// ...

Then add a collection form field to your CommentFormType with "type" of ImageFormType ( to be created ).

like image 88
Nicolai Fröhlich Avatar answered Nov 04 '22 09:11

Nicolai Fröhlich