Skip to content

Instantly share code, notes, and snippets.

@lifo101
Created July 26, 2016 12:07
Show Gist options
  • Save lifo101/563cc93f0c87ff6cf980171711e779bc to your computer and use it in GitHub Desktop.
Save lifo101/563cc93f0c87ff6cf980171711e779bc to your computer and use it in GitHub Desktop.
How to easily manage your OneToMany doctrine relationship in a Symfony form
<?php
/*
This is an example of how to easily manage a OneToMany relationship in a
Doctrine Entity with minimal code.
*/
$req = new Req();
$form = $this->createForm('AppBundle\Form\Type\MyType', $req);
$form->handleRequest($request);
if ($form->isValid()) {
// remove deleted tags (only needed on existing records)
// no need to create a cloned list before you create the form above, like some examples show.
if ($req->getId() !== null) {
/** @var PersistentCollection $original */
$original = $req->getTags();
// The snapshot has the original list before modification by the form
foreach ($original->getSnapshot() as $tag) {
if (!$req->getTags()->contains($tag)) {
$em->remove($tag);
}
}
}
try {
$em->persist($req);
$em->flush();
} catch (\Exception $e) {
// error
}
}
<?php
/**
* @ORM\Entity
*/
class Req
{
/**
* @var integer
*
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var ArrayCollection
*
* INVERSE SIDE
* @ORM\OneToMany(targetEntity="Network", mappedBy="request", cascade={"persist"})
*/
protected $tags;
}
<?php
class Tag
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*
* @var integer $id
*/
protected $id;
/**
* @var Req
*
* OWNING SIDE
* @ORM\ManyToOne(targetEntity="Req", inversedBy="tags", cascade={"persist"})
* @ORM\JoinColumn(onDelete="CASCADE")
*/
protected $req;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment