Skip to content

Instantly share code, notes, and snippets.

@sblondeau
Created July 13, 2018 14:05
Show Gist options
  • Save sblondeau/183b6c15226589c2deeeb7913e854945 to your computer and use it in GitHub Desktop.
Save sblondeau/183b6c15226589c2deeeb7913e854945 to your computer and use it in GitHub Desktop.
ManyToMany config
/**
* @var string
*
* @ORM\ManyToMany(targetEntity="Article", mappedBy="authors")
*/
private $articles;
/**
* Constructor
*/
public function __construct()
{
$this->articles = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add article
*
* @param \AppBundle\Entity\Article $article
*
* @return Author
*/
public function addArticle(\AppBundle\Entity\Article $article)
{
if (!$this->articles->contains($article)) {
$this->articles[] = $article;
$article->addAuthor($this);
}
return $this;
}
/**
* Remove article
*
* @param \AppBundle\Entity\Article $article
*/
public function removeArticle(\AppBundle\Entity\Article $article)
{
$this->articles->removeElement($article);
}
/**
* Get articles
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getArticles()
{
return $this->articles;
}
/**
* Displays a form to edit an existing author entity.
*
* @Route("/{id}/edit", name="author_edit")
* @Method({"GET", "POST"})
*/
public function editAction(Request $request, Author $author)
{
$deleteForm = $this->createDeleteForm($author);
$editForm = $this->createForm('AppBundle\Form\AuthorType', $author);
$originalArticles = new ArrayCollection();
foreach ($author->getArticles() as $article) {
$originalArticles->add($article);
}
$editForm->handleRequest($request);
$em = $this->getDoctrine()->getManager();
if ($editForm->isSubmitted() && $editForm->isValid()) {
foreach ($originalArticles as $article) {
if (false === $author->getArticles()->contains($article)) {
$article->getAuthors()->removeElement($author);
$em->persist($article);
// if you wanted to delete the Tag entirely, you can also do that
// $entityManager->remove($tag);
}
}
$em->persist($author);
$em->flush();
return $this->redirectToRoute('author_edit', array('id' => $author->getId()));
}
return $this->render('author/edit.html.twig', array(
'author' => $author,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment