Symfony 4嵌入了带有教义的一对多-多对一关系

时间:2018-08-07 07:39:54

标签: php symfony doctrine-orm symfony-forms symfony4

我正在关注how to embed a collection of forms上的symfony书 但是我有点卡住了。整个文档使我对教义应如何处理所有权方面感到困惑,我尽力实现了该示例,但没有运气。 我可以添加一个新条目,也可以将多个图像添加到我的条目中,但是在编辑孤儿上,不会被删除,有时我在文件上传方面遇到问题。 有人可以帮助我更好地理解如何实施它,并更好地解释一下所有权方面的工作方式和一般关系(我已经阅读了该学说的文档和symfony的书,昨天做了一些谷歌搜索,例如6个小时)。

无论如何,这是我的实体:

作品集编辑方法:

/**
 * @Route("/{id}/edit", name="portofolio_album_edit", methods="GET|POST")
 * @param Request $request
 * @param PortofolioAlbum $portofolioAlbum
 * @param EntityManagerInterface $entityManager
 * @return Response
 */
public function edit(Request $request, PortofolioAlbum $portofolioAlbum, EntityManagerInterface $entityManager): Response
{


    $originalImages = new ArrayCollection();

    // Create an ArrayCollection of the current Tag objects in the database
    foreach ($portofolioAlbum as $image) {
        $originalImages->add($image);
        exit(dump($image));
    }
    $form = $this->createForm(PortofolioAlbumType::class, $portofolioAlbum);
    $form->handleRequest($request);

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

        // remove the relationship between the tag and the Task
        foreach ($originalImages as $clonedImage) {

            if (false === $portofolioAlbum->getImages()->contains($clonedImage)) {
                $clonedImage->setAlbum(null);

                $entityManager->remove($clonedImage);
            }
        }

        $entityManager->persist($portofolioAlbum);
        $entityManager->flush();


        return $this->redirectToRoute('portofolio_album_edit', ['id' => $portofolioAlbum->getId()]);


    }

    return $this->render('Administration/PortofolioAlbum/edit.html.twig', [
        'portofolio_album' => $portofolioAlbum,
        'form' => $form->createView(),
    ]);
}

投资组合实体

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\PortofolioAlbumRepository")
 */
class PortofolioAlbum extends DateTime
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\PortofolioImage", mappedBy="album", cascade={"persist", "remove"}, orphanRemoval=true)
     *
     *
     */
    private $images;

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

    public function __toString()
    {
        // TODO: Implement __toString() method.
        return (string)$this->name;
    }

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

    public function addImage(PortofolioImage $portofolioImage)
    {


        $portofolioImage->setAlbum($this);

        $this->images->add($portofolioImage);

    }

    public function removeImage(PortofolioImage $portofolioImage)
    {
        $this->images->removeElement($portofolioImage);
        $portofolioImage->setAlbum(null);
        dump($portofolioImage);
        exit();
    }

}

PortfolioImage实体

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\PortofolioImageRepository")
 * @Vich\Uploadable()
 */
class PortofolioImage extends DateTime
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\Column(type="integer")
     */
    private $imageSize;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\PortofolioAlbum", inversedBy="images")
     */
    private $album;

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="portofolio_items", fileNameProperty="fileName", size="imageSize")
     *
     * @Assert\NotBlank(groups={"new"})
     *
     */
    private $imageFile;

    public function __toString()
    {
        return (string)$this->fileName;
        // TODO: Implement __toString() method.
    }

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

    /**
     * @return null|null
     */
    public function getFileName(): ?string
    {
        return $this->fileName;
    }

    public function setFileName(?string $fileName)
    {
        $this->fileName = $fileName;

        return $this;
    }

    public function getImageSize(): ?int
    {
        return $this->imageSize;
    }

    public function setImageSize(?int $imageSize): self
    {
        $this->imageSize = $imageSize;

        return $this;
    }

    public function getAlbum(): ?int
    {
        return $this->album;
    }

    public function setAlbum(PortofolioAlbum $album): PortofolioImage
    {
        $this->album = $album;

        return $this;
    }


    public function getImageFile(): ?File
    {
        return $this->imageFile;
    }

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the  update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     * @throws \Exception
     */
    public function setImageFile(?File $image = null): void
    {
        $this->imageFile = $image;

        if (null !== $image) {
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            //$this->setUpdatedAt(new \DateTime());
            $this->setUpdatedAt(new \DateTimeImmutable());
        }
    }
}

0 个答案:

没有答案