Step 9: Setting up an Admin Backend

Setting up an Admin Backend

Adding upcoming conferences to the database is the job of project admins. An admin backend is a protected section of the website where project admins can manage the website data, moderate feedback submissions, and more.

How can we create this fast? By using a bundle that is able to generate an admin backend based on the project’s model. EasyAdmin fits the bill perfectly.

Configuring EasyAdmin

First, add EasyAdmin as a project dependency:

  1. $ symfony composer req "admin:^3"

EasyAdmin automatically generates an admin area for your application based on specific controllers. Create a a new src/Controller/Admin/ directory where we will store these controllers:

  1. $ mkdir src/Controller/Admin/

To get started with EasyAdmin, let’s generate a “web admin dashboard” which will be the main entry point to manage the website data:

  1. $ symfony console make:admin:dashboard

Accepting the default answers creates the following controller:

src/Controller/Admin/DashboardController.php

  1. namespace App\Controller\Admin;
  2. use EasyCorp\Bundle\EasyAdminBundle\Config\Dashboard;
  3. use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;
  4. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. class DashboardController extends AbstractDashboardController
  8. {
  9. /**
  10. * @Route("/admin", name="admin")
  11. */
  12. public function index(): Response
  13. {
  14. return parent::index();
  15. }
  16. public function configureDashboard(): Dashboard
  17. {
  18. return Dashboard::new()
  19. ->setTitle('Guestbook');
  20. }
  21. public function configureMenuItems(): iterable
  22. {
  23. yield MenuItem::linktoDashboard('Dashboard', 'fa fa-home');
  24. // yield MenuItem::linkToCrud('The Label', 'icon class', EntityClass::class);
  25. }
  26. }

By convention, all admin controllers are stored under their own App\Controller\Admin namespace.

Access the generated admin backend at /admin as configured by the index() method; you can change the URL to anything you like:

Step 9: Setting up an Admin Backend - 图1

Boom! We have a nice looking admin interface shell, ready to be customized to our needs.

The next step is to create controllers to manage conferences and comments.

In the dashboard controller, you might have noticed the configureMenuItems() method which has a comment about adding links to “CRUDs”. CRUD is an acronym for “Create, Read, Update, and Delete”, the four basic operations you want to do on any entity. That’s exactly what we want an admin to perform for us; EasyAdmin even takes it to the next level by also taking care of searching and filtering.

Let’s generate a CRUD for conferences:

  1. $ symfony console make:admin:crud

Select 1 to create an admin interface for conferences and use the defaults for the other questions. The following file should be generated:

src/Controller/Admin/ConferenceCrudController.php

  1. namespace App\Controller\Admin;
  2. use App\Entity\Conference;
  3. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
  4. class ConferenceCrudController extends AbstractCrudController
  5. {
  6. public static function getEntityFqcn(): string
  7. {
  8. return Conference::class;
  9. }
  10. /*
  11. public function configureFields(string $pageName): iterable
  12. {
  13. return [
  14. IdField::new('id'),
  15. TextField::new('title'),
  16. TextEditorField::new('description'),
  17. ];
  18. }
  19. */
  20. }

Do the same for comments:

  1. $ symfony console make:admin:crud

The last step is to link the conference and comment admin CRUDs to the dashboard:

patch_file

  1. --- a/src/Controller/Admin/DashboardController.php
  2. +++ b/src/Controller/Admin/DashboardController.php
  3. @@ -2,6 +2,8 @@
  4. namespace App\Controller\Admin;
  5. +use App\Entity\Comment;
  6. +use App\Entity\Conference;
  7. use EasyCorp\Bundle\EasyAdminBundle\Config\Dashboard;
  8. use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;
  9. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;
  10. @@ -26,7 +28,8 @@ class DashboardController extends AbstractDashboardController
  11. public function configureMenuItems(): iterable
  12. {
  13. - yield MenuItem::linktoDashboard('Dashboard', 'fa fa-home');
  14. - // yield MenuItem::linkToCrud('The Label', 'fas fa-list', EntityClass::class);
  15. + yield MenuItem::linktoRoute('Back to the website', 'fas fa-home', 'homepage');
  16. + yield MenuItem::linkToCrud('Conferences', 'fas fa-map-marker-alt', Conference::class);
  17. + yield MenuItem::linkToCrud('Comments', 'fas fa-comments', Comment::class);
  18. }
  19. }

We have overridden the configureMenuItems() method to add menu items with relevant icons for conferences and comments icons and to add a link back to the website home page.

EasyAdmin exposes an API to ease linking to entity CRUDS via the MenuItem::linkToRoute() method.

The main dashboard page is empty for now. This is where you can display some statistics, or any relevant information. As we don’t have any important to display, let’s redirect to the conference list:

patch_file

  1. --- a/src/Controller/Admin/DashboardController.php
  2. +++ b/src/Controller/Admin/DashboardController.php
  3. @@ -7,6 +7,7 @@ use App\Entity\Conference;
  4. use EasyCorp\Bundle\EasyAdminBundle\Config\Dashboard;
  5. use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;
  6. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;
  7. +use EasyCorp\Bundle\EasyAdminBundle\Router\CrudUrlGenerator;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. @@ -17,7 +18,10 @@ class DashboardController extends AbstractDashboardController
  11. */
  12. public function index(): Response
  13. {
  14. - return parent::index();
  15. + $routeBuilder = $this->get(CrudUrlGenerator::class)->build();
  16. + $url = $routeBuilder->setController(ConferenceCrudController::class)->generateUrl();
  17. +
  18. + return $this->redirect($url);
  19. }
  20. public function configureDashboard(): Dashboard

When displaying entity relationships (the conference linked to a comment), EasyAdmin tries to use a string representation of the conference. By default, it uses a convention that uses the entity name and the primary key (like Conference #1) if the entity does not define the “magic” __toString() method. To make the display more meaningful, add such a method on the Conference class:

patch_file

  1. --- a/src/Entity/Conference.php
  2. +++ b/src/Entity/Conference.php
  3. @@ -44,6 +44,11 @@ class Conference
  4. $this->comments = new ArrayCollection();
  5. }
  6. + public function __toString(): string
  7. + {
  8. + return $this->city.' '.$this->year;
  9. + }
  10. +
  11. public function getId(): ?int
  12. {
  13. return $this->id;

Do the same for the Comment class:

patch_file

  1. --- a/src/Entity/Comment.php
  2. +++ b/src/Entity/Comment.php
  3. @@ -48,6 +48,11 @@ class Comment
  4. */
  5. private $photoFilename;
  6. + public function __toString(): string
  7. + {
  8. + return (string) $this->getEmail();
  9. + }
  10. +
  11. public function getId(): ?int
  12. {
  13. return $this->id;

You can now add/modify/delete conferences directly from the admin backend. Play with it and add at least one conference.

Step 9: Setting up an Admin Backend - 图2

Add some comments without photos. Set the date manually for now; we will fill-in the createdAt column automatically in a later step.

Step 9: Setting up an Admin Backend - 图3

Customizing EasyAdmin

The default admin backend works well, but it can be customized in many ways to improve the experience. Let’s do some simple changes to the Comment entity to demonstrate some possibilities:

patch_file

  1. --- a/src/Controller/Admin/CommentCrudController.php
  2. +++ b/src/Controller/Admin/CommentCrudController.php
  3. @@ -3,7 +3,15 @@
  4. namespace App\Controller\Admin;
  5. use App\Entity\Comment;
  6. +use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  7. +use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
  8. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
  9. +use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
  10. +use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
  11. +use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
  12. +use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
  13. +use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
  14. +use EasyCorp\Bundle\EasyAdminBundle\Filter\EntityFilter;
  15. class CommentCrudController extends AbstractCrudController
  16. {
  17. @@ -12,14 +20,44 @@ class CommentCrudController extends AbstractCrudController
  18. return Comment::class;
  19. }
  20. - /*
  21. + public function configureCrud(Crud $crud): Crud
  22. + {
  23. + return $crud
  24. + ->setEntityLabelInSingular('Conference Comment')
  25. + ->setEntityLabelInPlural('Conference Comments')
  26. + ->setSearchFields(['author', 'text', 'email'])
  27. + ->setDefaultSort(['createdAt' => 'DESC']);
  28. + ;
  29. + }
  30. +
  31. + public function configureFilters(Filters $filters): Filters
  32. + {
  33. + return $filters
  34. + ->add(EntityFilter::new('conference'))
  35. + ;
  36. + }
  37. +
  38. public function configureFields(string $pageName): iterable
  39. {
  40. - return [
  41. - IdField::new('id'),
  42. - TextField::new('title'),
  43. - TextEditorField::new('description'),
  44. - ];
  45. + yield AssociationField::new('conference');
  46. + yield TextField::new('author');
  47. + yield EmailField::new('email');
  48. + yield TextareaField::new('text')
  49. + ->hideOnIndex()
  50. + ;
  51. + yield TextField::new('photoFilename')
  52. + ->onlyOnIndex()
  53. + ;
  54. +
  55. + $createdAt = DateTimeField::new('createdAt')->setFormTypeOptions([
  56. + 'html5' => true,
  57. + 'years' => range(date('Y'), date('Y') + 5),
  58. + 'widget' => 'single_text',
  59. + ]);
  60. + if (Crud::PAGE_EDIT === $pageName) {
  61. + yield $createdAt->setFormTypeOption('disabled', true);
  62. + } else {
  63. + yield $createdAt;
  64. + }
  65. }
  66. - */
  67. }

To customize the Comment section, listing the fields explicitly in the configureFields() method lets us order them the way we want. Some fields are further configured, like hiding the text field on the index page.

The configureFilters() methods defines which filters to expose on top of the search field.

Step 9: Setting up an Admin Backend - 图4

These customizations are just a small introduction of the possibilities given by EasyAdmin.

Play with the admin, filter the comments by conference, or search comments by email for instance. The only issue is that anybody can access the backend. Don’t worry, we will secure it in a future step.

  1. $ symfony run psql -c "TRUNCATE conference RESTART IDENTITY CASCADE"

Going Further


This work, including the code samples, is licensed under a Creative Commons BY-NC-SA 4.0 license.