简体   繁体   English

Symfony 4如何上传与oneToMany相关的多个图像?

[英]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 谢谢您的帮助

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- 有两种解决方法: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 2-在Image实体中使用生命周期回调将PreUpdate和PrePersist事件上的图像上传到服务器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM