src/Controller/Admin/BlogController.php line 57

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace App\Controller\Admin;
  11. use App\Entity\Post;
  12. use App\Form\PostType;
  13. use App\Repository\PostRepository;
  14. use App\Security\PostVoter;
  15. use Doctrine\ORM\EntityManagerInterface;
  16. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  17. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  18. use Symfony\Component\Form\Extension\Core\Type\SubmitType;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpFoundation\Response;
  21. use Symfony\Component\Routing\Annotation\Route;
  22. /**
  23.  * Controller used to manage blog contents in the backend.
  24.  *
  25.  * Please note that the application backend is developed manually for learning
  26.  * purposes. However, in your real Symfony application you should use any of the
  27.  * existing bundles that let you generate ready-to-use backends without effort.
  28.  *
  29.  * See http://knpbundles.com/keyword/admin
  30.  *
  31.  * @Route("/admin/post")
  32.  * @IsGranted("ROLE_ADMIN")
  33.  *
  34.  * @author Ryan Weaver <weaverryan@gmail.com>
  35.  * @author Javier Eguiluz <javier.eguiluz@gmail.com>
  36.  */
  37. class BlogController extends AbstractController
  38. {
  39.     /**
  40.      * Lists all Post entities.
  41.      *
  42.      * This controller responds to two different routes with the same URL:
  43.      *   * 'admin_post_index' is the route with a name that follows the same
  44.      *     structure as the rest of the controllers of this class.
  45.      *   * 'admin_index' is a nice shortcut to the backend homepage. This allows
  46.      *     to create simpler links in the templates. Moreover, in the future we
  47.      *     could move this annotation to any other controller while maintaining
  48.      *     the route name and therefore, without breaking any existing link.
  49.      *
  50.      * @Route("/", methods="GET", name="admin_index")
  51.      * @Route("/", methods="GET", name="admin_post_index")
  52.      */
  53.     public function index(PostRepository $posts): Response
  54.     {
  55.         $authorPosts $posts->findBy(['author' => $this->getUser()], ['publishedAt' => 'DESC']);
  56.         return $this->render('admin/blog/index.html.twig', ['posts' => $authorPosts]);
  57.     }
  58.     /**
  59.      * Creates a new Post entity.
  60.      *
  61.      * @Route("/new", methods="GET|POST", name="admin_post_new")
  62.      *
  63.      * NOTE: the Method annotation is optional, but it's a recommended practice
  64.      * to constraint the HTTP methods each controller responds to (by default
  65.      * it responds to all methods).
  66.      */
  67.     public function new(Request $requestEntityManagerInterface $entityManager): Response
  68.     {
  69.         $post = new Post();
  70.         $post->setAuthor($this->getUser());
  71.         // See https://symfony.com/doc/current/form/multiple_buttons.html
  72.         $form $this->createForm(PostType::class, $post)
  73.             ->add('saveAndCreateNew'SubmitType::class);
  74.         $form->handleRequest($request);
  75.         // the isSubmitted() method is completely optional because the other
  76.         // isValid() method already checks whether the form is submitted.
  77.         // However, we explicitly add it to improve code readability.
  78.         // See https://symfony.com/doc/current/forms.html#processing-forms
  79.         if ($form->isSubmitted() && $form->isValid()) {
  80.             $entityManager->persist($post);
  81.             $entityManager->flush();
  82.             // Flash messages are used to notify the user about the result of the
  83.             // actions. They are deleted automatically from the session as soon
  84.             // as they are accessed.
  85.             // See https://symfony.com/doc/current/controller.html#flash-messages
  86.             $this->addFlash('success''post.created_successfully');
  87.             if ($form->get('saveAndCreateNew')->isClicked()) {
  88.                 return $this->redirectToRoute('admin_post_new');
  89.             }
  90.             return $this->redirectToRoute('admin_post_index');
  91.         }
  92.         return $this->render('admin/blog/new.html.twig', [
  93.             'post' => $post,
  94.             'form' => $form->createView(),
  95.         ]);
  96.     }
  97.     /**
  98.      * Finds and displays a Post entity.
  99.      *
  100.      * @Route("/{id<\d+>}", methods="GET", name="admin_post_show")
  101.      */
  102.     public function show(Post $post): Response
  103.     {
  104.         // This security check can also be performed
  105.         // using an annotation: @IsGranted("show", subject="post", message="Posts can only be shown to their authors.")
  106.         $this->denyAccessUnlessGranted(PostVoter::SHOW$post'Posts can only be shown to their authors.');
  107.         return $this->render('admin/blog/show.html.twig', [
  108.             'post' => $post,
  109.         ]);
  110.     }
  111.     /**
  112.      * Displays a form to edit an existing Post entity.
  113.      *
  114.      * @Route("/{id<\d+>}/edit", methods="GET|POST", name="admin_post_edit")
  115.      * @IsGranted("edit", subject="post", message="Posts can only be edited by their authors.")
  116.      */
  117.     public function edit(Request $requestPost $postEntityManagerInterface $entityManager): Response
  118.     {
  119.         $form $this->createForm(PostType::class, $post);
  120.         $form->handleRequest($request);
  121.         if ($form->isSubmitted() && $form->isValid()) {
  122.             $entityManager->flush();
  123.             $this->addFlash('success''post.updated_successfully');
  124.             return $this->redirectToRoute('admin_post_edit', ['id' => $post->getId()]);
  125.         }
  126.         return $this->render('admin/blog/edit.html.twig', [
  127.             'post' => $post,
  128.             'form' => $form->createView(),
  129.         ]);
  130.     }
  131.     /**
  132.      * Deletes a Post entity.
  133.      *
  134.      * @Route("/{id}/delete", methods="POST", name="admin_post_delete")
  135.      * @IsGranted("delete", subject="post")
  136.      */
  137.     public function delete(Request $requestPost $postEntityManagerInterface $entityManager): Response
  138.     {
  139.         if (!$this->isCsrfTokenValid('delete'$request->request->get('token'))) {
  140.             return $this->redirectToRoute('admin_post_index');
  141.         }
  142.         // Delete the tags associated with this blog post. This is done automatically
  143.         // by Doctrine, except for SQLite (the database used in this application)
  144.         // because foreign key support is not enabled by default in SQLite
  145.         $post->getTags()->clear();
  146.         $entityManager->remove($post);
  147.         $entityManager->flush();
  148.         $this->addFlash('success''post.deleted_successfully');
  149.         return $this->redirectToRoute('admin_post_index');
  150.     }
  151. }