SonataAdminBundle + FOSUserBundle: Have a GOOD base project

Publié le par Jordan Samouh

This article is going to explain /how to/ correctly create a backoffice
(admin panel + crud) in Symfony 2.

Generally, for any web project, you need a back office to manager
entities, data, users and groups and, fortunately today there are a
number of bundles for Symfony 2 which allow you to create an admin panel
quickly.

(.. because it is boring to redevelop phpmyadmin we can save ourselves
the effort and reutilise existing Symfony2 bundles)

What bundles do you need to install?

[FOSUserBundle]
    git=git://github.com/FriendsOfSymfony/FOSUserBundle.git
    target=bundles/FOS/UserBundle

[SonatajQueryBundle]
    git=https://github.com/sonata-project/SonatajQueryBundle.git
    target=/bundles/Sonata/jQueryBundle

[SonataAdminBundle]
    git=https://github.com/sonata-project/SonataAdminBundle.git
    target=/bundles/Sonata/AdminBundle

[MenuBundle]
    git=https://github.com/KnpLabs/KnpMenuBundle.git
    target=/bundles/Knp/Bundle/MenuBundle

[KnpMenu]
    git=https://github.com/KnpLabs/KnpMenu.git
    target=/knp/menu

[SonataUserBundle]
    git=git://github.com/sonata-project/SonataUserBundle.git
    target=/bundles/Sonata/UserBundle

[SonataEasyExtendsBundle]
    git=git://github.com/sonata-project/SonataEasyExtendsBundle.git
    target=/bundles/Sonata/EasyExtendsBundle

[SonataDoctrineORMAdminBundle]
    git=https://github.com/sonata-project/SonataDoctrineORMAdminBundle.git
    target=/bundles/Sonata/DoctrineORMAdminBundle

Add the namespaces to app/autoload.php

// app/autoload.php
$loader->registerNamespaces(array(
    // ...
    'FOS'              => __DIR__.'/../vendor/bundles',
    'Sonata'           => __DIR__.'/../vendor/bundles',
    'Application'      => __DIR__,
    'Knp'              => array(
                          __DIR__.'/../vendor/bundles',
                          __DIR__.'/../vendor/knp/menu/src',
                          ),
    // ...
));

Enable the bundles in app/AppKernel.php

// app/AppKernel.php
    public function registerBundles()
    {
        $bundles = array(
            // ...
            new FOS\UserBundle\FOSUserBundle(),
            new Sonata\jQueryBundle\SonatajQueryBundle(),
            new Sonata\AdminBundle\SonataAdminBundle(),
            new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new Sonata\UserBundle\SonataUserBundle('FOSUserBundle'),
            new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),
            // ...
        );
        // ...
    }

Add

# app/config/config.yml
fos_user:
    db_driver: orm
    firewall_name: main
    user_class: Application\Sonata\UserBundle\Entity\User

Run

php app/console sonata:easy-extends:generate SonataUserBundle

It is going to generate an Application UserBundle, but you can use your own.
To develop your understanding, do this by default and try after to readapt the code with your UserBundle

Add the new Bundle to app/AppKernel.php

// app/AppKernel.php
    public function registerbundles()
    {
        $bundles = array(
            // Application Bundles
            // ...
            new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
            // ...
        );
        // ...
    }

Add routing

# app/config/routing.yml
fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

fos_user_register:
    resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
    prefix: /register

fos_user_resetting:
    resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
    prefix: /resetting

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /change-password

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

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

soanata_user:
    resource: '@SonataUserBundle/Resources/config/routing/admin_security.xml'
    prefix: /admin

sonata_user_impersonating:
    pattern: /
    defaults: { _controller: SonataPageBundle:Page:catchAll }

Add the following to app/config/security.yml

# app/config/security.yml
security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
        SONATA:
            - ROLE_SONATA_PAGE_ADMIN_PAGE_EDIT  # if you are not using acl then this line must be uncommented

    providers:
        fos_userbundle:
            id: fos_user.user_manager

    firewalls:

        # -> custom firewall for the admin area of the URL
        admin:
            pattern:      /admin(.*)
            form_login:
                provider:       fos_userbundle
                login_path:     /admin/login
                use_forward:    false
                check_path:     /admin/login_check
                failure_path:   null
            logout:
                path:           /admin/logout
            anonymous:    true
        # -> end custom configuration

        # defaut login area for standard users
        main:
            pattern:      .*
            form_login:
                provider:       fos_userbundle
                login_path:     /login
                use_forward:    false
                check_path:     /login_check
                failure_path:   null
            logout:       true
            anonymous:    true

# ...

    access_control:
        # URL of FOSUserBundle which need to be available to anonymous users
        - { path: ^/_wdt, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/_profiler, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }

        # -> custom access control for the admin area of the URL
        - { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/login-check$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        # -> end

        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }

        # Secured part of the site
        # This config requires being logged for the whole site and having the admin role for the admin part.
        # Change these rules to adapt them to your needs
        - { path: ^/admin, role: [ROLE_ADMIN, ROLE_SONATA_ADMIN] }
        - { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }
# ...

Do theses commands for the end

php app/console doctrine:schema:update --force
php app/console assets:install web
php app/console cache:clear
php app/console fos:user:create admin admin@example.com password --super-admin

You need to enable your translator in /app/config.yml

framework:
    translator: ~

That’s it!!!
As you can see, a lotof things must be done for it to
work

But after this initial step you will only need to modify the XML files
and the Admin class ((plural?)) of your new bundles.

With this demo you should have a functioning admin interface for « user »
and « group » entities. This is accomplished only with the following 2
files:
- Setup UserAdmin Class (found in AdminFolder in the bundle SonataUserBundle) (see more info in SonataAdminBundle Doc)
- Setup admin_orm.xml (found in Ressources/coinfig in the bundle SonataUserBundle) (see more info in SonataAdminBundle Doc)

When you need to administer more entities in your application, editing
these two files is all you will need to do.

For more information, see: http://sonata-project.org/bundles/admin/master/doc/index.html

Cette entrée a été publiée dans Symfony 2 Utils. Vous pouvez la mettre en favoris avec ce permalien.



9 réponses à SonataAdminBundle + FOSUserBundle: Have a GOOD base project

  1. Nelson dit :

    Hello. I’m stucked since a few hours in (probably) a stupid error, buy maybe is a compatibility issue across Symfony versions. The exception message is this:

    #php app/console sonata:easy-extends:generate SonataUserBundle
    PHP Fatal error: Class 'Application\Sonata\UserBundle\ApplicationSonataUserBundle' not found in /var/www/sonataadmin/app/AppKernel.php on line 28

    Everything seems to be on the place, in fact I have another test project that follow the steps of the official Sonata Project tutorial and it doesn’t complain about that class.

    I’m working on Symfony 2.0.14, by the way.

    • Glouzy201 dit :

      Salut Nelson, Me too I meet this error but the solution I used is simpl:

      Install SonataDoctrineExtension and then

      use this lines in your Autoload:

      if (!function_exists(‘intl_get_error_code’)) {
      #… rest of you code
      $loader->registerNamespaces(
      array(
      #… rest of you code
      ‘Sonata’ => array(
      __DIR__ . ‘/../vendor/bundles’,
      __DIR__ . ‘/../vendor/sonata-doctrine-extensions/src’
      ),
      #… rest of you code
      )
      );
      #… rest of you code
      }

      $loader->add(‘Application’, __DIR__);
      #… rest of you code

      #GOOD LUCK

  2. Nelson dit :

    Hello there. I’m using Symfony 2.0.15 and I’ve just got another error message, but this time I have the solution.

    $ php app/console doctrine:schema:update --force

    [Doctrine\DBAL\DBALException]
    Unknown column type json requested.

    doctrine:schema:update [--complete] [--dump-sql] [--force] [--em[="..."]]

    The solution is just install the bundle SonataDoctrineExtension and another couple in order to resolve the dependency

    [SonataDoctrineExtensions]
    git=git@github.com:sonata-project/sonata-doctrine-extensions.git
    target=/sonata-doctrine-extensions

    [SonataBlockBundle]
    git=http://github.com/sonata-project/SonataBlockBundle.git
    target=/bundles/Sonata/BlockBundle
    version=origin/2.0

    [SonataCacheBundle]
    git=http://github.com/sonata-project/SonataCacheBundle.git
    target=/bundles/Sonata/CacheBundle
    version=origin/2.0

    And more important yet add a new key in app/config/config.yml like this:

    doctrine
    dbal:
    types:
    json: Sonata\Doctrine\Types\JsonType

    Let’s repeat the doctrine command once again:

    $ php app/console doctrine:schema:update --force
    Updating database schema...
    Database schema updated successfully! "14" queries were executed

    And that’s it! you can go on with the rest.

    Anyway, in the tutorial is missing the command to install all the bundles in the deps file, is pretty obvious, I know, but there’s a lot of Symfony newbies reading this. The command is:

    php bin/vendors install

  3. Didi dit :

    Thanks for this very good article.
    Could you explain us how to do the same with Composer ? without the deps file and with composer.json.

    • Didi dit :

      I think the first step must be to add theses lines in the composer.json after « require »:
      ,
      « friendsofsymfony/user-bundle »: « * »,
      « sonata-project/jquery-bundle »: « * »,
      « sonata-project/admin-bundle »: « * »,
      « sonata-project/user-bundle »: « * »,
      « sonata-project/easy-extends-bundle »: « * »,
      « sonata-project/doctrine-orm-admin-bundle »: « * »,
      « knplabs/knp-menu »: « * »,
      « knplabs/knp-menu-bundle »: « * »

      and then : php composer.phar update

      But i don’t know what to do next.

  4. Didi dit :

    Ok, i think i arrived to something.
    I don’t know how to edit a comment so I post a 3rd one. You shouldn’t validate my comments, and put a summary of all that in your article (after checking it ^^)

    So after  » php composer.phar update  » do all the rest of the article except the autoload.php part (just add the line i put down there). and add theses lines to the configuration files :
    _______________________
    #config.yml
    doctrine:
    dbal:
    # …
    types:
    json: Sonata\Doctrine\Types\JsonType

    framework:
    translator: { fallback: %locale% }

    sonata_block:
    default_contexts: [cms]
    blocks:
    sonata.admin.block.admin_list:
    contexts: [admin]
    sonata.block.service.text:
    sonata.block.service.action:
    sonata.block.service.rss:
    _______________________________
    // app/autoload.php
    $loader->add(‘Application’, __DIR__);

    _____________________________
    // app/AppKernel.php
    new Sonata\BlockBundle\SonataBlockBundle(),
    new Sonata\CacheBundle\SonataCacheBundle(),

  5. jdivins dit :

    Hello Jodan,
    I am following your tutorial, and maybe there is one mistake, you’ve written:
    soanata_user:
    instead of
    sonata_user:
    in routing.yml code
    Is correct?

  6. gtrennert dit :

    Hello,
    Nice !
    I only have issues when on a multilingual site – I added prefix: /{_locale}/admin on routes but now my firewall stopped working and admin area is no more secured.
    I tried something like this : pattern: ^/{_locale}/admin(.*) – but no way
    How can I get admin area work for different languages ?

  7. Thank you very much for this tutorial! Are you using Symfony 2.1 already? Have you, by any chance, built a Symfony2.1 base project including SonataAdminBundle + FOSUserBundle yet?
    Cheers!
    Timon

Laisser un commentaire

Votre adresse de messagerie ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*


3 * = twenty four

Vous pouvez utiliser ces balises et attributs HTML : <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>