Sonata Admin Bundle One-to-Many relationship not saving foreign ID

前端 未结 6 1330
粉色の甜心
粉色の甜心 2020-12-14 12:23

I have a problem with the SonataAdminBunle in combination with symfony 2.2. I have a Project entity and a ProjectImage entity and specified a One-to-Many relationship betwee

6条回答
  •  星月不相逢
    2020-12-14 12:56

    Although unrelated, I'd slighty tweak your One-to-Many annotation:

    class Project
    {
        /**
         * @ORM\OneToMany(targetEntity="ProjectImage", mappedBy="project", cascade={"persist"}, orphanRemoval=true)
         * @ORM\OrderBy({"id" = "ASC"})
         */
        private $images;
    }
    

    Back on track, your annotations and Sonata Admin forms look fine, so I'm pretty sure you're missing one of those methods in your Project entity class:

    public function __construct() {
        $this->images = new \Doctrine\Common\Collections\ArrayCollection();
    }
    
    public function setImages($images)
    {
        if (count($images) > 0) {
            foreach ($images as $i) {
                $this->addImage($i);
            }
        }
    
        return $this;
    }
    
    public function addImage(\Acme\YourBundle\Entity\ProjectImage $image)
    {
        $image->setProject($this);
    
        $this->images->add($image);
    }
    
    public function removeImage(\Acme\YourBundle\Entity\ProjectImage $image)
    {
        $this->images->removeElement($image);
    }
    
    public function getImages()
    {
        return $this->Images;
    }
    

    And in your Admin class:

    public function prePersist($project)
    {
        $this->preUpdate($project);
    }
    
    public function preUpdate($project)
    {
        $project->setImages($project->getImages());
    }
    

提交回复
热议问题