/** * Edits an existing Tag entity. * * @Route("/{id}", name="tag_update") * @Method("PUT") * @Template("PaxyknoxNewsBundle:Tag:edit.html.twig") */ public function updateAction(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('PaxyknoxNewsBundle:Tag')->find($id); if (!$entity) { throw $this->createNotFoundException('Unable to find Tag entity.'); } // before Tag change // get list of all Articles with this Tag // $articles = $entity->getArticles(); $oldArticlesIdsList = new \Doctrine\Common\Collections\ArrayCollection(); foreach ($articles as $article) { $oldArticlesIdsList[] = $article->getId(); } $editForm = $this->createEditForm($entity); $editForm->handleRequest($request); if ($editForm->isValid()) { try { // Tag entity $em->flush(); // For each selected Article on edit form get its id // // Check if it is in $oldArticlesIdsList // - true remove it from the list // - false find Article and set Tag on it // // Articles that will remain on the list no longer need Tag set on it // $data = $request->request->all(); foreach ($data as $dataParameter => $dataParameterValue) { if (isset($dataParameterValue["articles"])) { foreach ($dataParameterValue["articles"] as $articleIdString) { $articleId = (int) $articleIdString; if ($oldArticlesIdsList->contains($articleId)) { $oldArticlesIdsList->removeElement($articleId); } else { $article = $em->getRepository('PaxyknoxNewsBundle:Article')->find($articleId); $article->addTag($entity); } } } } if (!$oldArticlesIdsList->isEmpty()) { foreach ($oldArticlesIdsList as $articleId) { $article = $em->getRepository('PaxyknoxNewsBundle:Article')->find($articleId); $article->removeTag($entity); $oldArticlesIdsList->removeElement($articleId); } } // Article Entity $em->flush(); $flashMessage = $this->get('translator')->trans('flash.tag.update_success', array('%s%' => $entity->getName())); $this->get('session')->getFlashBag()->add('success', $flashMessage); } catch (\Doctrine\DBAL\DBALException $e) { $flashMessage = $this->get('translator')->trans('flash.tag.update_warning'); $this->get('session')->getFlashBag()->add('warning', $flashMessage); return $this->redirect($this->generateUrl('tag_edit', array('id' => $id))); } return $this->redirect($this->generateUrl('tag_show', array('id' => $id))); } return array('entity' => $entity, 'edit_form' => $editForm->createView()); }