Setting up the admin builder

By the end of this lesson, you’ll have an administration area which makes managing the dynamic parts of your app simple, creating a management interface for the blog system in the process. Along the way, we’ll be:

  • Setting up an administration service
  • Creating your first admin

Follow along using the code available from this GIT repository.
Start - ready_to_go_user_system
End - setting_up_the_admin_builder

Installing Sonata Admin

Sonata Admin is a CRUD workflow that helps to quickly glue data components to an interface. It features everything you’d expect from an administration interface forming a solid solution and for the lacking features, makes every step extendable / customisable.

Unlike FOSUser, which includes functionality for handling different database engines built in, Sonata seperates each in to a bundle of it's own. In this tutorial, we are using MySQL so need the ORM (Object Relational Mapping) version.

  1. composer require sonata-project/admin-bundle \
  2.                  sonata-project/doctrine-orm-admin-bundle

You may notice that more than two packages are downloaded when running the above; this means Sonata has external dependencies. Always read the documentation first (which you should anyway), bundles which have external dependencies may require additional configuration. In the case of Sonata, it is only the KnpMenu builder, an OO navigation builder.

Just like we hooked FOSUser up to Symfony in the AppKernel, we're going to do the same for Sonata Admin, and KnpMenu.

  1. // # app/AppKernel.php
  2.  
  3. // A presentation platform built on Bootstrap
  4. new Sonata\CoreBundle\SonataCoreBundle(),
  5. new Sonata\BlockBundle\SonataBlockBundle(),
  6. new Knp\Bundle\MenuBundle\KnpMenuBundle(),
  7. // The Sonata Admin functionality
  8. new Sonata\AdminBundle\SonataAdminBundle(),
  9. new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),

With regard to configuring both Sonata and these other bundles, copy the code below in to your config.yml file. If you want to know how I discovered these options, the first time I set this bundle up I RTFM.

  1. # app/config/config.yml
  2.  
  3. # Hooking Sonata Admin in to the Block bundle
  4. sonata_block:
  5.    default_contexts: [cms]
  6.    blocks:
  7.        # enable the SonataAdminBundle block
  8.        sonata.admin.block.admin_list:
  9.            contexts: [admin]
  1. # app/config/routing.yml
  2.  
  3. # Default routes for Sonata Admin
  4. admin_area:
  5.    resource: "@SonataAdminBundle/Resources/config/routing/sonata_admin.xml"
  6.    prefix: /admin
  7.  
  8. # Allow generation of routes for our admins
  9. _sonata_admin:
  10.    resource: .
  11.    type: sonata_admin
  12.    prefix: /admin

With everything setup to handle admin creation, there is already an interface available: http://127.0.0.1/app_dev.php/admin.

At this point, you may be presented by a very simply page without any kind of styling. The reason this happens is due to the page trying to load assets which don't yet exist within the web path.

If you take a look in your web directory, there is a folder called bundles, this folder is a place where third party code (and even your own bundles) dumps their assets. After running the following command, reload your browser (on the admin page) and you should get a different picture.

  1. # The symlink option creates shortcuts to the bundles if possible to try and save space
  2. php bin/console assets:install --symlink

Creating your first Admin

Declaring the Service

The Symfony web kernel interacts with many objects and provides an interface for various PHP tasks (plugins, classes, event hooks) to be part of the Symfony pipeline. For accessing objects, there is a dedicated handler called the Service Container. In order to make the code available to Symfony as a service, it needs to be defined in the configuration under the services heading.

Sonata works by declaring each entity administration as a service and uses the tag feature to get recognised.

  1. # app/config/services.yml
  2. services:
  3.   sonata.admin.post:
  4.     class: AppBundle\Admin\PostAdmin
  5.     tags:
  6.       - { name: sonata.admin, manager_type: orm, group: "Blog Management", label: "Posts"}
  7.     arguments: [~, AppBundle\Entity\Post, ~]
  8.     calls:
  9.       - [ setTranslationDomain, [AppBundle]]
  • sonata.admin.post - the Symfony reference to the name of the service
  • class - points to the name space of the class the service will use
  • tags - name: sonata.admin will be recognised by the main admin service
  • arguments - the constructor parameters being used, in the case of Sonata, the second parameter is the data object
  • calls - An object method that will be called upon initialisation

Building the admin

With configuration setup and aready making the admin service aware of the data object, the only thing left to do is create the actual admin class.

In the configuration, we have already chosen the namespace our admin will be located in: AppBundle\Admin\PostAdmin. We could use a different location but (when creating all our code in the AppBundle namespace), this is standard practise and what you will find documented by the authors of Sonata so, and it's best to code in line with expectations if possible.

  1. <?php
  2. // # src/AppBundle/Admin/PostAdmin.php
  3. namespace AppBundle\Admin;
  4.  
  5. // The base Sonata object
  6. use Sonata\AdminBundle\Admin\AbstractAdmin;
  7. // Used for including CRUD
  8. use Sonata\AdminBundle\Datagrid\ListMapper;
  9. // The Edit form
  10. use Sonata\AdminBundle\Form\FormMapper;
  11.  
  12. class PostAdmin extends AbstractAdmin
  13. {
  14.    // Edit view
  15.    protected function configureFormFields(FormMapper $formMapper)
  16.    {
  17.       $formMapper
  18.           ->add('title', 'text')
  19.           ->add('summary', 'text')
  20.           ->add('content', 'text');
  21.    }
  22.    // CRUD view
  23.    protected function configureListFields(ListMapper $listMapper)
  24.    {
  25.       $listMapper->addIdentifier('title');
  26.    }
  27. }

The admin definition above is the minimal amount of code we need in order to get things running; there are many options available to Sonata Admin and there is some excellent documentation available on readthedocs which you are strongly suggested to read.

With a basic admin setup, refresh your administration area. If everything went right, you should now be able to manage basic blog entries for yourself with no code intervention

Exercises

Communication, our greatest tool

Whether you want to connect, have a problem I can help with or simply want to drop a line, I welcome your words!