Setting up a Symfony2 Project with FOSUserBundle, SonataUserBundle and SonataAdminBundle

Tested with Symfony Standard 2.0.7 (http://symfony.com/download?v=Symfony_Standard_Vendors_2.0.7.tgz)

This is basically a merge of the installation-guides of FOSUserBundle (https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/index.md), SonataAdminBundle (http://sonata-project.org/bundles/admin/master/doc/reference/installation.html) and SonataUserBundle (http://sonata-project.org/bundles/user/master/doc/reference/installation.html)

  1. Add
    [FOSUserBundle]
        git=git://github.com/FriendsOfSymfony/FOSUserBundle.git
        target=bundles/FOS/UserBundle
    
    [SonatajQueryBundle]
        git=http://github.com/sonata-project/SonatajQueryBundle.git
        target=/bundles/Sonata/jQueryBundle
    
    [SonataAdminBundle]
        git=http://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=http://github.com/sonata-project/SonataDoctrineORMAdminBundle.git
        target=/bundles/Sonata/DoctrineORMAdminBundle

    to your deps file. (Don’t forget the trailing newline.)

  2. Run
    php bin/vendors install --reinstall
  3. 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',
                              ),
        // ...
    ));
  4. 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(),
                // ...
            );
            // ...
        }
  5. Add
    # app/config/config.yml
    fos_user:
        db_driver: orm
        firewall_name: main
        user_class: Application\Sonata\UserBundle\Entity\User

    to app/config/config.yml

  6. Run
    php app/console sonata:easy-extends:generate SonataUserBundle
  7. Add the new Bundle to app/AppKernel.php
    // app/AppKernel.php
        public function registerbundles()
        {
            $bundles = array(
                // Application Bundles
                // ...
                new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
                // ...
            );
            // ...
        }
  8. Add
    # 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

    to app/config/routing.yml

  9. 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 }
    # ...
  10. Update your DB-Schema. Run
    php app/console doctrine:schema:update --force
  11. Now, install the assets from the different bundles:
    php app/console assets:install web
  12. Clear your cache:
    php app/console cache:clear
  13. You can create an admin-user and a test-user with the following commands.
    php app/console fos:user:create admin admin@example.com password --super-admin
    php app/console fos:user:create testuser test@example.com password
  14. You need to enable your translator in /app/config.yml.
  15. Create app/Application/Sonata/UserBundle/Recources/translations/SonataUserBundle.en.ymlwith the following content:
    # app/Application/Sonata/UserBundle/Recources/translations/SonataUserBundle.en.yml
    form:
      label_username:             Username
      label_email:                Email
      label_plain_password:       Password (Plain)
      label_groups:               Groups
      label_roles:                Roles
      label_locked:               Locked
      label_expired:              Expired
      label_enabled:              Enabled
      label_credentials_expired:  Credentials Expired
      label_name:                 Name
    
    list:
      label_username:             Username
      label_email:                Email
      label_enabled:              Enabled
      label_locked:               Locked
      label_created_at:           Created At
      label_roles:                Roles
      label_name:                 Name
    
    filter:
      label_username:             Username
      label_locked:               Locked
      label_email:                Email
      label_id:                   ID
      label_name:                 Name

44 thoughts on “Setting up a Symfony2 Project with FOSUserBundle, SonataUserBundle and SonataAdminBundle”

  1. First of all, thanks so much for posting this.
    When I tried adding a user using the command line app/console fos:user:create I got a Runtime Exception “No encoder has been configured for account “Application\Sonata\UserBundle\Entity\User”.
    What I did to fix this was to add the following encoder in the /app/security.yml file:

    encoders:
            FOS\UserBundle\Model\UserInterface: sha512

    which now allows me to add users.

    1. Hey, thanks for your reply.
      It seems the exception is only thrown on newer versions. Everything was fine until i updated my vendors.

      I have updated my Tutorial.

    2. In app/config/security.yml….write this code

      security:
          encoders:
              FOS\UserBundle\Model\UserInterface: sha512
              Webmuch\UserBundle\Entity\User: 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 }
      
      
      #....
      
  2. I cant thank you enough for this!! If you are in the NYC area, I will buy you many beers!

    I do have a question though.
    I am usin gsym 2.0.8 and just went through this tutorial and getting a ‘The server returned a “500 Internal Server Error”.’ when trying to view: /admin/sonata/user/user/list . /admin/sonata/user/group/list works fine.

    Any ideas?
    Thanks again.

    1. Yes indeed I have. I had the same Problem and I saw that a ‘homepage’ route is missing. Something to do with super admins able to switch between users and they are redirected to the ‘homepage’ route. So you just have to define a ‘homepage’ route.

      1. Is this ‘homepage’ route to be defined in the SonataUser admin_security.xml file or in the main routing.yml file?
        I have tried in the main routing.yml file and still getting the 505 error (as well as the 404 when i try to go to my app ‘index/homepage’ of http://app/ )

        1. got this fixed. I needed to clear the cache it seems. I was clearing it from dev, but was calling the prod env. Thanks again.

          1. Could you provide an example of a useful homepage route here? It is not clear to me what “homepage” should point to.
            Thanks.

  3. i hav installed bundle and see some error too on /admin/sonata/user/user/list

    “An exception has been thrown during the rendering of a template (“Catchable Fatal Error: Object of class DateTime could not be converted to string in /home/vhost/my/slideshow/docs/app/cache/dev/twig/7e/46/ccc953b0a01b20bbd35f594d12d6.php line 68″) in SonataAdminBundle:CRUD:base_list_field.html.twig at line 21.”

    what to do?

  4. Hi, when i try to do step 10, got this error:

    php app/console doctrine:schema:update –force

    [RuntimeException]
    Error with class Application\Sonata\UserBundle\Entity\Group : Property groups does not exist

    [ReflectionException]
    Property groups does not exist

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

    I use sf 2.0.9

    What can i do to fix this problem ?

    thanks
    Bye

  5. you have to add in your app/config/routing.yml these lines :

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

    as found in this (recent) diff file :
    https://github.com/sonata-project/sandbox/commit/804cea79a2e31ea26347dfac95ad5237d0b6a537#diff-0

  6. i have this error after installing and at the 1st time i got the login window and after login nothing work

    the error is

    No route found for “GET /admin/login”
    or
    No route found for “GET /admin/”

  7. done all the tutorial with 2.0.11 stable

    the dashboard login form works but when logged in:
    i got
    The function “sonata_block_render” does not exist in SonataAdminBundle:Core:dashboard.html.twig at line 21

    did i forget something ?
    thx for reply

    1. understand… i should have put Block Bundle

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

      ++

  8. For Symfony 2.0.12

    deps should look like:

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

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

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

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

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

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

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

    [Exporter]
    git=http://github.com/sonata-project/exporter.git
    target=/exporter

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

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

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

    [/code]

    config.yml

    [code]
    fos_user:
    db_driver: orm
    firewall_name: main
    user_class: Application\Sonata\UserBundle\Entity\User

    sonata_block:
    default_contexts: [cms]
    blocks:
    sonata.admin.block.admin_list:
    contexts: [admin]

    #sonata.admin_doctrine_orm.block.audit:
    # contexts: [admin]

    sonata.block.service.text:
    sonata.block.service.action:
    sonata.block.service.rss:

    # Some specific block from the SonataMediaBundle
    #sonata.media.block.media:
    #sonata.media.block.gallery:
    #sonata.media.block.feature_media:
    [/code]

    autoload.php

    [code]
    'FOS' => __DIR__.'/../vendor/bundles',
    'Sonata' => __DIR__.'/../vendor/bundles',
    'Application' => __DIR__,
    'Knp' => array(
    __DIR__.'/../vendor/bundles',
    __DIR__.'/../vendor/knp/menu/src',
    ),
    'Exporter' => __DIR__.'/../vendor/exporter/lib',

    [/code]

    AppKernel.php

    [code]
    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(),
    new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
    new Sonata\BlockBundle\SonataBlockBundle(),
    new Sonata\CacheBundle\SonataCacheBundle(),
    [/code]

  9. Hi everybody,
    I am new to Symfony2 and i have some problems with installing the Sonata with Fos Bundle based on this tutorial.
    Step 10 is somehow not working for me
    (php app/console doctrine:schema:update –force)
    But when i go to AppKernel and i remove this line:
    new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
    i have no problems with the above command.
    Still i can’t build tables for using FOSuserBundle, can somebody help me ?
    I am trying to finish this tutorial a week around and i do not have any success!

  10. Having to tried to get this working myself, and then via following your tutorial, I’m still running into the same problem:

    Everything seems fine, except that I cannot login, on login I get redirected to my destination i.e. homepage, but I’m still anon. When registering however, it logs me in successfully, but once logged out I’m back in the same position.

    Any ideas?

    1. Check your security file. You might have 2 different firewalls. The doc says firewalls don’t share security context. So if you are redirecting to a page that is not in the same security context, you will not be considered logged in.

  11. thanks for this tuto

    I am new to Symfony2 and i have some problems with creating of user with Fos Bundle based on this tutorial.
    Step 13 I can´t create an admin-user and a test-user with the command. in this step

    i receive this message :

    PHP Fatal error: Call to undefined method Symfony\Bundle\DoctrineBundle\Registry::getManager() in C:\wamp\www\Symfony\app\cache\dev_new\appDevDebugProjectConta
    iner__5019ef4c5a436__.php on line 1043

    Anyone can can help me, please

    1. I actually had to change app/autoload.php to:

      'Sonata' => array(
      __DIR__.'/../vendor/bundles',
      __DIR__.'/../vendor/SonataDoctrineExtensions/src',
      ),

      to get past this error:
      Fatal error: Class ‘Sonata\Doctrine\Types\JsonType’ not found in /usr/local/symfony/vendor/doctrine-dbal/lib/Doctrine/DBAL/Types/Type.php on line 142

      when trying to execute the schema update.

  12. Before you try:
    php app/console doctrine:schema:update –force

    And get the error:
    “Fatal error: Class Sonata\UserBundle\Entity\BaseUser contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Symfony\Component\Security\Core\User\UserInterface::equals) in /Applications/MAMP/htdocs/Symfony/vendor/bundles/Sonata/UserBundle/Entity/BaseUser.php on line 20″

    Update your deps to limit the FOSUserBundle version — the new one is meant for newer Symfony.

    [FOSUserBundle]
    git=git://github.com/FriendsOfSymfony/FOSUserBundle.git
    target=bundles/FOS/UserBundle
    version=origin/1.2.x

    The version line fixes it!! “php bin/vendors install” if you need to downgrade.

    1. I’m using symfony2 . And i got same error . Tries to fix version of FOSUserBundle 1.2.x. Still i’m getting same error. Any idea?

  13. I followed the steps up to 12. But I’m getting an error when clearing the cache:

    [Doctrine\ORM\Mapping\MappingException]
    Class Application\Sonata\UserBundle\Entity\User is not a valid entity or mapped super class.

    Any ideas what’s wrong?

      1. I fixed installing github in my machine (then I don’t have the error of permission denied). Then I launch
        php bin/vendors install
        and everything works for me

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="">