Crown Backend
Crown Backend

Reputation: 171

Symfony 4 how to upload multiple images in relation oneToMany?

I come to you because I have a little trouble I block

I would like to be able to upload several images for an article, but I can not get through I'm blocking I do not understand how to do it

I share my code a bit, if you can help me or if you have some tutorial that can help me because I look but some tutorial are not very explicit

in my controller :

public function addArticle(Request $request): Response
{
    $article = new Article();
    $form = $this->createForm(ArticleType::class, $article);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()) {

        $file = $article->getImages();

        $fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();

        try {
            $file->move(
                $this->getParameter('images_directory'),
                $fileName
            );
        } catch (FileException $e) {
            // ... handle exception if something happens during file upload
        }

        $em = $this->getDoctrine()->getManager();
        $em->persist($article);
        $em->flush();
    }

    return $this->render('backOffice/home/add-article.html.twig', [
        'form' => $form->createView()
    ]);
}

my entitys :

class Article
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 5,
     *      max = 255,
     *      minMessage = "Votre titre doit contenir au minimum {{ limit }} caractères",
     *      maxMessage = "Votre titre doit contenir au maximum {{ limit }} caractères")
     */
    private $title;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     * @Assert\Length(
     *     min="20",
     *     minMessage="Votre description doit contenir au minimum {{ limit }} caractères"
     * )
     */
    private $description;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $updatedAt;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Image", mappedBy="article")
     * @Assert\NotBlank()
     * @Assert\File(
     *     mimeTypes={"image/jpeg", "image/png", "image/gif"},
     *     mimeTypesMessage = "Please upload a valid Image"
     *     )
     */
    private $images;

    /**
     * Article constructor.
     * @throws \Exception
     */
    public function __construct()
    {
        $this->images = new ArrayCollection();
        $this->createdAt = new \DateTime('now', new \DateTimeZone('Europe/Paris'));
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(?\DateTimeInterface $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @return Collection|Image[]
     */
    public function getImages(): Collection
    {
        return $this->images;
    }

    public function addImage(Image $image): self
    {
        if (!$this->images->contains($image)) {
            $this->images[] = $image;
            $image->setArticle($this);
        }

        return $this;
    }

    public function removeImage(Image $image): self
    {
        if ($this->images->contains($image)) {
            $this->images->removeElement($image);
            // set the owning side to null (unless already changed)
            if ($image->getArticle() === $this) {
                $image->setArticle(null);
            }
        }

        return $this;
    }

}

in my my entity image :

class Image
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Article", inversedBy="images")
     * @ORM\JoinColumn(nullable=false)
     */
    private $article;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getArticle(): ?Article
    {
        return $this->article;
    }

    public function setArticle(?Article $article): self
    {
        $this->article = $article;

        return $this;
    }

}

thank you for your help

Upvotes: 0

Views: 1112

Answers (1)

JessGabriel
JessGabriel

Reputation: 1072

Images and article are in one-to-many relationship, but your code treat it like an one-to-one relationship. There are two way to solve this : 1-

    $files = $article->getImages();
    foreach ($files as $file) {
        $fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();

          try {
                $file->move(
                  $this->getParameter('images_directory'),
                  $fileName
            );
          } catch (FileException $e) {
        // ... handle exception if something happens during file upload
          }
    }

2- Use lifecycle callback in your Image entity to upload your image to server on PreUpdate and PrePersist event

Upvotes: 1

Related Questions