Symfony2 Sonata Admin Bundle

Symfony2 Sonata Admin Bundle
Sonata Admin Bundle

In this post you will be able to work with Sonata Admin Bundle. Just follow the below step and at the end of this post you will get full functional working with this bundle.
To use Sonata Admin Bundle you have to install and configure Symfony2 framework. I hope you guys are ready with it.

Installation

1.1.    Downloading the cod

Use composer to manage your dependencies and download SonataAdminBundle:

>php composer.phar require sonata-project/admin-bundle

You’ll be asked to type in a version constraint. ‘dev-master’ will get you the latest version, compatible with the latest Symfony2 version. Check packagist for older versions:

Please provide a version constraint for the sonata-project/admin-bundle requirement: dev-master

1.2.    Downloading a storage bundle

SonataAdminBundle can work with several storage mechanisms. We are using Doctrine ORM so we will install SonataDoctrineORMAdminBundle.

>composer require sonata-project/doctrine-orm-admin-bundle

You’ll be asked to type in a version constraint. ‘dev-master’ will usually get you the latest, bleeding edge version. Check packagist for stable and legacy versions:
Please provide a version constraint for the sonata-project/

doctrine-orm-admin-bundle requirement: dev-master

1.3.    Enabling SonataAdminBundle and its dependencies

SonataAdminBundle relies on other bundles to implement some features. Besides the storage layer mentioned on step 2, there are other bundles needed for SonataAdminBundle to work:

  • SonataBlockBundle
  • SonatajQueryBundle
  • KnpMenuBundle (Version 1.1.*)

These bundles are automatically downloaded by composer as a dependency of SonataAdminBundle. However, you have to enable them in your AppKernel.php, and configure them manually. Don’t forget to enable SonataAdminBundle too:

// app/AppKernel.php
public function registerBundles()
{
       return array(
        // ...

        // Add your dependencies
        new Sonata\BlockBundle\SonataBlockBundle(),
        new Sonata\jQueryBundle\SonatajQueryBundle(),
        new Knp\Bundle\MenuBundle\KnpMenuBundle(),
        new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),

        // Then add SonataAdminBundle
        new Sonata\AdminBundle\SonataAdminBundle(),
        // ...
        );
}

1.4.    Configuring SonataAdminBundle dependencies

SonataAdminBundle provides a SonataBlockBundle block that’s used on the administration dashboard. To be able to use it, make sure it’s enabled on SonataBlockBundle’s configuration:

YAML

# app/config/config.yml
sonata_block:
        default_contexts: [cms]
        blocks:
        # Enable the SonataAdminBundle block
        sonata.admin.block.admin_list:
                contexts: [admin]
        # Your other blocks

1.5.    Cleaning up

Now, install the assets from the bundles:

php app/console assets:install web

Usually, when installing new bundles, it’s good practice to also delete your cache:

php app/console cache:clear
Getting started with SonataAdminBundle

If you followed the installation instructions, SonataAdminBundle should be installed but inaccessible. You first need to configure it for your models before you can start using it. Here is a quick checklist of what is needed to quickly setup SonataAdminBundle and create your first admin interface for the models of your application:

  • Step 1: Define SonataAdminBundle routes
  • Step 2: Create an Admin class
  • Step 3: Create an Admin service
  • Step 4: Configuration

Step 1: Define SonataAdminBundle routes

To be able to access SonataAdminBundle’s pages, you need to add its routes to your application’s routing file:
YAML

# app/config/routing.yml
admin:

        resource:@SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
        prefix: /admin

_sonata_admin:
        resource: .
            type: sonata_admin
            prefix: /admin

At this point you can already access the (empty) admin dashboard by visiting the url: http://yoursite.local/admin/dashboard.

Step 2: Create an Admin class

SonataAdminBundle helps you manage your data using a graphic interface that will let you create, update or search your model’s instances. Those actions need to be configured, which is done using an Admin class.
An Admin class represents the mapping of your model to each administration action. In it, you decide which fields to show on a listing, which to use as filters or what to show on an creation/edition form.
The easiest way to create an Admin class for your model is to extend the Sonata\AdminBundle\Admin\Admin class.
Suppose your JigarUserBundle has a User entity. This is how a basic Admin class for it could look like:

namespace Jigar\UserBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
class UserAdmin extends Admin {

protected function configureFormFields(FormMapper $formMapper)
{
   $formMapper
      ->add('username', 'text', array('label' => 'User Name'))
      ->add('firstname')
      ->add('lastname')
      ->add('email')
      ->add('password');
}

protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
   $datagridMapper->add('username', null, array('label' => 'User Name')
      ->add('email');
}

protected function configureListFields(ListMapper $listMapper)
{
   $listMapper
      ->addIdentifier('username')
      ->add('email')
      ->addIdentifier('enabled', null, array('template' =>
         'JigarUserBundle:CRUD:status_field.html.twig'))
      ->addIdentifier('roles', null, array(
         'template' => 'JigarUserBundle:CRUD:list_roles.html.twig',
      ))
      ->add('phone')
      ->add('_action', 'actions', array(
         'actions' => array(
         'show' => array(),
         'edit' => array(),
         'delete' => array()
      )
      ));
}
protected function configureShowField(ShowMapper $showMapper)
{
   $showMapper
      ->add('username')
      ->add('email');
}

Step 3: Create an Admin service

Now that you have created your Admin class, you need to create a service for it. This service needs to have the sonata.admin tag, which is your way of letting SonataAdminBundle know that this particular service represents an Admin class:
Create either a new admin.xml or admin.yml file inside the Jigar/UserBundle/Resources/config/ folder:
YAML

services:
   sonata.admin.user:
     class: Jigar\UserBundle\Admin\UserAdmin
     tags:
        - { name: sonata.admin, manager_type: orm, group: "User", label: "User" }
     arguments:
        - ~
        - Jigar\UserBundle\Entity\User
        - ~
     calls:
        - [ setTranslationDomain, [JigarUserBundle]]

Now that you have a configuration file with you admin service, you just need to tell Symfony2 to load it. There are two ways to do so:

  • Importing it in the main config.yml

Include your new configuration file in the main config.yml (make sure that you use the correct file extension):
YAML

# app/config/config.yml
imports:
     - { resource: @JigarUserBundle/Resources/config/admin.xml }
  • Have your bundle load it

#Jigar/UserBundle/DependencyInjection/JigarUserBundleExtension.php for YAML configurations

use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\Config\FileLocator;

public function load(array $configs, ContainerBuilder $container)
{
   $configuration = new Configuration();
   $config = $this->processConfiguration($configuration, $configs);

   $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));

   $loader->load('services.yml');

   $loader->load('admin.yml');

}

Step 4: Configuration

At this point you have basic administration actions for your model. If you visit http://yoursite.local/admin/dashboard again, you should now see a panel with your model mapped. You can start creating, listing, editing and deleting instances.

The above image shows the home page of admin panel listing the three different entities User, Product and Category.