siwymilek
siwymilek

Reputation: 815

Create record with relation to child

I have two Entities Page (name, description ...) and Seo (page_id, title ...). I built Form Page with SeoType as child. After sending the form I receive Page entity with filled Seo section, but without page_id (what is obvious).

So is even possible to store Page, so as to set page_id in seo section automatically?

Sorry, but I can not express themselves clearly.

My dumped object:

enter image description here

Upvotes: 0

Views: 35

Answers (1)

Alsatian
Alsatian

Reputation: 3135

According to the symfony documentation, here : http://symfony.com/doc/current/cookbook/form/form_collections.html (see 'Doctrine: Cascading Relations and saving the "Inverse" side')

If your form data class is the owning side :

class Seo
{
    /**
     * @ORM\ManyToOne(targetEntity="AppBundle:Page", cascade={"persist"})
     */
    private $page;
}

If your form is on the inverse side, you have to add the owned entity to deal like so :

class Seo
{
     /**
     * @ORM\OneToMany(targetEntity="AppBundle:Page", mappedBy="seo")
     */
    private $pages;

    public function addPage(Page $page)
    {
        $page->setSeo($this);

        $this->pages->add($page);
    }
}

class Page
{
     /**
     * @ORM\ManyToOne(targetEntity="AppBundle:Seo", inversedBy="pages")
     */
    private $seo;

    public function setSeo(Seo $seo)
    {
        $this->seo = $seo;
    }
}

Upvotes: 1

Related Questions