Created
July 26, 2016 12:07
-
-
Save lifo101/563cc93f0c87ff6cf980171711e779bc to your computer and use it in GitHub Desktop.
How to easily manage your OneToMany doctrine relationship in a Symfony form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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