FOSUserBundle of Symfony2

FOSUserBundle of Symfony2

What is Bundle?
Bundles are pieces of software, which is created for first feature development. Symfony has lots of bundles in the web. You can find all amazing bundles information in which are categorized by popularity, rating, recommendation etc.

What is FOSUserBundle?
The FOSUserBundle adds support for a database-backed user system in Symfony2. It provides a flexible framework for user management that aims to handle common tasks such as user registration and password retrieval.

Features include:
– Users can be stored via Doctrine ORM, MongoDB/CouchDB ODM or Propel
– Registration support, with an optional confirmation per email
– Password reset support
– Unit tested

Lets start a fresh project with Symfony2 –

$ composer create-project symfony/framework-standard-edition fosuser/

Installing symfony/framework-standard-edition (v2.6.6)
- Installing symfony/framework-standard-edition (v2.6.6)
Loading from cache

Created project in fosuser/
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
- Installing doctrine/lexer (v1.0.1)
Loading from cache
Generating autoload files
Would you like to install Acme demo bundle? [y/N] N
Creating the "app/config/parameters.yml" file
Some parameters are missing. Please provide them.
database_driver (pdo_mysql):
database_host (
database_port (null):
database_name (symfony): fosuser
database_user (root):
database_password (null):
mailer_transport (smtp):
mailer_host (
mailer_user (null):
mailer_password (null):
locale (en):
secret (ThisTokenIsNotSoSecretChangeIt): fosuser
Clearing the cache for the dev environment with debug true
Trying to install assets as symbolic links.
Installing assets for Symfony\Bundle\FrameworkBundle into web/bundles/framework
The assets were installed using symbolic links.
Installing assets for Sensio\Bundle\DistributionBundle into web/bundles/sensiodistribution
The assets were installed using symbolic links.

Now go to with your browser –


If you see something like this then you are good to go—

Symfony2 installation success

Scary, right!!!

We need to create a bundle for our project, first. Let’s do it—

$ php app/console generate:bundle --namespace=Custom/UserBundle

Welcome to the Symfony2 bundle generator

In your code, a bundle is often referenced by its name. It can be the
concatenation of all namespace parts but it's really up to you to come
up with a unique name (a good practice is to start with the vendor name).
Based on the namespace, we suggest CustomUserBundle.

Bundle name [CustomUserBundle]:

The bundle can be generated anywhere. The suggested default directory uses
the standard conventions.

Target directory [/Applications/XAMPP/xamppfiles/htdocs/fosuser/src]:

Determine the format to use for the generated configuration.

Configuration format (yml, xml, php, or annotation): yml

To help you get started faster, the command can generate some
code snippets for you.

Do you want to generate the whole directory structure [no]? yes

Summary before generation

You are going to generate a "Custom\UserBundle\CustomUserBundle" bundle
in "/Applications/XAMPP/xamppfiles/htdocs/fosuser/src/" using the "yml" format.

Do you confirm generation [yes]?

Bundle generation

Generating the bundle code: OK
Checking that the bundle is autoloaded: OK
Confirm automatic update of your Kernel [yes]?
Enabling the bundle inside the Kernel: OK
Confirm automatic update of the Routing [yes]?
Importing the bundle routing resource: OK

You can now start using the generated code!


Now change the following line of code from app/config/config.yml

framework: translator: ~

Let’s download our FOSUserBundle using composer. In our composer.json add –

"require": {
"friendsofsymfony/user-bundle": "~1.3"

Tell the composer to download it –

$ php composer update friendsofsymfony/user-bundle

Now tell the Kernel, we have new bundle in app/AppKernel.php.

$bundles = array(        
 // ...         
new FOS\UserBundle\FOSUserBundle(),     

Create a User.php file in src/Custom/UserBundle/Entity/

namespace Custom\UserBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;

 * @ORM\Entity
 * @ORM\Table(name="fos_user")
class User extends BaseUser
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
    protected $id;

    public function __construct()

Update app/config/security.yml as follows –

id: fos_user.user_provider.username

FOS\UserBundle\Model\UserInterface: sha512

pattern: ^/
provider: fos_userbundle
csrf_provider: form.csrf_provider
logout: true
anonymous: true

- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin/, role: ROLE_ADMIN }


Add the following lines of code in app/config/config.yml

db_driver: orm
firewall_name: main
user_class: Custom\UserBundle\Entity\User

Now, add the following routing info in app/config/routing.yml

resource: "@FOSUserBundle/Resources/config/routing/security.xml"

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

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

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

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

Now update your schema –

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

Let’s check what we have created so far for in our db –

fosuser db

We haven’t created any field but all the fields created by FOSUserBundle!!!

Now check what functionalities we are going to get for free –

$ php app/console router:debug
[router] Current routes
Name Method Scheme Host Path
_wdt ANY ANY ANY /_wdt/{token}
_profiler_home ANY ANY ANY /_profiler/
_profiler_search ANY ANY ANY /_profiler/search
_profiler_search_bar ANY ANY ANY /_profiler/search_bar
_profiler_purge ANY ANY ANY /_profiler/purge
_profiler_info ANY ANY ANY /_profiler/info/{about}
_profiler_phpinfo ANY ANY ANY /_profiler/phpinfo
_profiler_search_results ANY ANY ANY /_profiler/{token}/search/results
_profiler ANY ANY ANY /_profiler/{token}
_profiler_router ANY ANY ANY /_profiler/{token}/router
_profiler_exception ANY ANY ANY /_profiler/{token}/exception
_profiler_exception_css ANY ANY ANY /_profiler/{token}/exception.css
_configurator_home ANY ANY ANY /_configurator/
_configurator_step ANY ANY ANY /_configurator/step/{index}
_configurator_final ANY ANY ANY /_configurator/final
_twig_error_test ANY ANY ANY /_error/{code}.{_format}
user ANY ANY ANY /user/
user_show ANY ANY ANY /user/{id}/show
user_new ANY ANY ANY /user/new
user_create POST ANY ANY /user/create
user_edit ANY ANY ANY /user/{id}/edit
user_update POST|PUT ANY ANY /user/{id}/update
user_delete POST|DELETE ANY ANY /user/{id}/delete
custom_user_homepage ANY ANY ANY /hello/{name}
homepage ANY ANY ANY /app/example

Now go to http://localhost/fosuser/web/app_dev.php/login

What you see? The login form is ready to go. But we don’t have any user in our database.

Let’s create one user to check our form is working –

$ php app/console fos:user:create
Please choose a username:shahjalal
Please choose an
Please choose a password:shahjalal
Created user shahjalal

Try to login and go to your login page again. Now you will see the logout link.

The forms are looking ugly right!!!

fos user profile

Let’s make it beautiful. In src/Custom/UserBundle we have CustomUserBundle.php update is as follows. Because we want to overwrite the default templates we got with FOSUserBundle.


namespace Custom\UserBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CustomUserBundle extends Bundle
	public function getParent()
        return 'FOSUserBundle';

Now create a layout.html.twig file inside src/Custom/UserBundle/Resources/views folder –

{% extends '::base.html.twig' %}

{% block body %}
    {{ block('fos_user_content') }}
{% endblock %}

We are extending our base layout which is inside app/Resources/views folder. Now update —

<!DOCTYPE html>
        <meta charset="UTF-8" />
        <title>{% block title %}Welcome!{% endblock %}</title>
        {% block stylesheets %}
        <link rel="stylesheet" type="text/css" href="{{ asset('css/bootstrap-3.3.4-dist/css/bootstrap.min.css') }}">
        {% endblock %}
        <link rel="icon" type="image/x-icon" href="{{ asset('favicon.ico') }}" />
        <div class="container">
            <div class="hero-unit">
                <h1>Symfony2 FOSUserBundle Tutorial</h1>
            <div class="row">
                <div class="span12">
                    {% block body %}{% endblock %}

                <p>&copy; Shahjalal {{ '' | date('Y') }} </p>
        {% block javascripts %}{% endblock %}

For our purpose lets change our login form. So, copy FOS/UserBundle/Resources/views/Security folder to our src/Custom/UserBundle/Resources/views folder. And add some div in login form.

{% extends "FOSUserBundle::layout.html.twig" %}

{% block fos_user_content %}
{% if error %}
    <div>{{ error|trans({}, 'FOSUserBundle') }}</div>
{% endif %}

<form action="{{ path("fos_user_security_check") }}" method="post">
    <input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />

    <label for="username">{{ 'security.login.username'|trans({}, 'FOSUserBundle') }}</label>
    <input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />

    <label for="password">{{ 'security.login.password'|trans({}, 'FOSUserBundle') }}</label>
    <input type="password" id="password" name="_password" required="required" />

    <input type="checkbox" id="remember_me" name="_remember_me" value="on" />
    <label for="remember_me">{{ 'security.login.remember_me'|trans({}, 'FOSUserBundle') }}</label>
    <input type="submit" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans({}, 'FOSUserBundle') }}" />
{% endblock fos_user_content %}

Now go to your login form again. All are well organized. You can add as much style as possible –

fosuser login page

For simplicity I have only shown one form. But you can change all the styles for all pages. The rules are same…

You can download all the source code from — Source code

Happy coding… 🙂

FOSUserBundle of Symfony2

Leave a Reply

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