getUserCurrent(); $productFamily = $this->_getProductFamily($request); if($user && $productFamily) { if ($user->getFavoriteProductFamilies()->contains($productFamily)) { $user->removeFavoriteProductFamily($productFamily); $isFavorite = false; $message = 'Le produit a bien été supprimé de vos favoris'; } else { $user->addFavoriteProductFamily($productFamily); $isFavorite = true; $message = 'Le produit a bien été ajouté à vos favoris'; } $this->_saveUser($user); return new JsonResponse([ 'return' => 'success', 'is_favorite' => $isFavorite, 'message' => $message ]); } else { return $this->_errorResponse(); } } /** * @Route("/favorite/add", name="lc_frontend_favorite_add") */ public function add(Request $request) { $user = $this->getUserCurrent(); $productFamily = $this->_getProductFamily($request); if($user && $productFamily) { $user->addFavoriteProductFamily($productFamily); $this->_saveUser($user); return new JsonResponse([ 'return' => 'success', 'message' => 'Le produit a bien été ajouté à vos favoris' ]); } else { return $this->_errorResponse(); } } /** * @Route("/favorite/delete", name="lc_frontend_favorite_delete") */ public function delete(Request $request) { $user = $this->getUserCurrent(); $productFamily = $this->_getProductFamily($request); if($user && $productFamily) { $user->removeFavoriteProductFamily($productFamily); $this->_saveUser($user); return new JsonResponse([ 'return' => 'success', 'message' => 'Le produit a bien été supprimé de vos favoris' ]); } else { return $this->_errorResponse(); } } private function _saveUser($user) { $entityManager = $this->getEntityManager(); $entityManager->update($user); $entityManager->flush(); } private function _getProductFamily($request) { $idProductFamily = $request->request->get('idProductFamily'); if($idProductFamily) { $productFamily = $this->getProductFamilyContainer()->getStore()->getOneById($idProductFamily); } if (isset($productFamily) && $productFamily) { return $productFamily; } } private function _errorResponse() { return new JsonResponse([ 'return' => 'error', 'message' => 'Une erreur est survenue.' ]); } }