public function save(Item $item, ArrayCollection $oldAttributes) { // add EntityManager to short variable $em = $this->getEntityManager(); // remove removed attributes // oldAttributes is ArrayCollection cannot // be casted to empty array if empty Helper::loopCollection(function ($collectionItem) use($item, $em) { if (false === $item->getAttributes()->contains($collectionItem)) { // delete attribute permanently $em->remove($collectionItem); } }, $oldAttributes); // associate attribute with item // attributes is persisted automatically Helper::loopCollection(function ($collectionItem) use($item) { $collectionItem->setItem($item); }, $item->getAttributes()); if (!$item->getId()) { // set data for new item $item->setCreatedAt(new \DateTime()); $item->setSlug(Helper::makeSlugs($item->getName())); } // set when was item updated then persist it // and flush to database $item->setUpdatedAt(new \DateTime()); $em->persist($item); $em->flush(); }
public function newAction(Request $request) { // create new category $category = new Category(); // inicialize new category form type to render and validate form $categoryFormType = new CategoryType(); // create the form $form = $this->createForm($categoryFormType, $category); // handle http request $form->handleRequest($request); // check if form is submitted and is valid if ($form->isSubmitted() && $form->isValid()) { // set data for new category if (!$category->getId()) { $category->setSlug(Helper::makeSlugs($category->getName())); } // persist changes on category $this->em()->persist($category); // flush new data to database $this->em()->flush(); if ($category->getId()) { // display success message $this->addFlash("success", $this->get("translator")->trans("category.has.been.saved")); return $this->redirectToRoute("erik_app_admin_category_edit", array("id" => $category->getId())); } else { // display error message $this->addFlash("danger", $this->get("translator")->trans("category.has.been.not.saved")); } } // return http response with rendered template return new Response($this->renderView("::backend/pages/category/edit.html.twig", array("form" => $form->createView(), "category" => $category))); }