User registration with Symfony

User registration with Symfony

In this tutorial, we will learn about the registration of new users with Symfony2. Hope you have already read earlier tutorials. Because, this is an extension of previous one. We will work on the same code as well as we will also add more.


Let’s assume, we need to register our new users. For simplicity, we will only take username and password from the new user (but, anyway you can add more fields as you needed) and the admin will access to manage the users. New users only can view the book lists (And of course, you can add more functionality and make more smart system just changing in the view, nothing else). So, let’s start.

First we need to generate our user entity. And you have already known entities are work like model in Symfony.

Now open your command prompt and go to your project folder. And write the entity generation command.

$ php app/console doctrine:generate:entity

  Welcome to the Doctrine2 entity generator  

This command helps you generate Doctrine2 entities.

First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.

The Entity shortcut name: CustomBookBundle:User

Determine the format to use for the mapping information.

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

Instead of starting with a blank entity, you can add some fields now.
Note that the primary key will be added automatically (named id).

Available types: array, simple_array, json_array, object, 
boolean, integer, smallint, bigint, string, text, datetime, datetimetz, 
date, time, decimal, float, blob, guid.

New field name (press <return> to stop adding fields): username
Field type [string]: 
Field length [255]: 50

New field name (press <return> to stop adding fields): password
Field type [string]: 
Field length [255]: 64

New field name (press <return> to stop adding fields): 

Do you want to generate an empty repository class [no]? 

  Summary before generation  

You are going to generate a "CustomBookBundle:User" Doctrine2 entity
using the "annotation" format.

Do you confirm generation [yes]? 

  Entity generation  

Generating the entity code: OK

  You can now start using the generated code!  


Yes, our entity is done. Now go to src/Custom/BookBundle/Entity/User.php, which contains our user entity code. For the sake of interaction with user and the database, we need to use UserInterface interface. So, let’s do it as follows-

namespace Custom\BookBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

 * User
 * @ORM\Table()
 * @ORM\Entity
class User implements UserInterface
     * @var integer
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
    private $id;

     * @var string
     * @ORM\Column(name="username", type="string", length=50)
    private $username;

     * @var string
     * @ORM\Column(name="password", type="string", length=64)
    private $password;

     * Get id
     * @return integer 
    public function getId()
        return $this->id;

     * Set username
     * @param string $username
     * @return User
    public function setUsername($username)
        $this->username = $username;

        return $this;

     * Get username
     * @return string 
    public function getUsername()
        return $this->username;

     * Set password
     * @param string $password
     * @return User
    public function setPassword($password)
        $this->password = password_hash($password, PASSWORD_BCRYPT) ;

        return $this;

     * Get password
     * @return string 
    public function getPassword()
        return $this->password;

    public function getSalt(){
        return null;

    public function getRoles(){
        return array('ROLE_USER');

    public function eraseCredentials(){


Need to be mention, UserInterface is an interface, so it has three methods, we need to implement, getSalt(),getRoles(), eraseCredentials(). Here, getRoles() will return ‘ROLE_USER‘ role.

In our setPassword() method in line no 79, we have encrypt user password using bcrypt.

Now again in the command prompt write the following command to push the entity to the database, so that it can create table for our users. No need to be worried. Our previous table will be intact.

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

You can check your database with phpmyadmin, if our new table has created. If everything is fine, you will see a new table has created in our database with two fields, username and password.

Now we will create our CRUD through command prompt. We have done this before, can you remember!!!

$ php app/console generate:doctrine:crud 
  Welcome to the Doctrine2 CRUD generator  

This command helps you generate CRUD controllers and templates.

First, you need to give the entity for which you want to generate a CRUD.
You can give an entity that does not exist yet and the wizard will help
you defining it.

You must use the shortcut notation like AcmeBlogBundle:Post.

The Entity shortcut name: CustomBookBundle:User

By default, the generator creates two actions: list and show.
You can also ask it to generate "write" actions: new, update, and delete.

Do you want to generate the "write" actions [no]? yes

Determine the format to use for the generated CRUD.

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

Determine the routes prefix (all the routes will be "mounted" under this
prefix: /prefix/, /prefix/new, ...).

Routes prefix [/user]: 

  Summary before generation  

You are going to generate a CRUD controller for "CustomBookBundle:User"
using the "yml" format.

Do you confirm generation [yes]? 

  CRUD generation  

Generating the CRUD code: OK
Generating the Form code: OK
Confirm automatic update of the Routing [yes]? 
Importing the CRUD routes: OK

  You can now start using the generated code!  


You can check the controller folder; a new controller has created for user as well as the view.

By default, in our form the password field type is text. We want to change it password. Because logical, right?

So open src/Custom/BookBundle/Form/UserType.php and add the field type as password in line 5.

public function buildForm(FormBuilderInterface $builder, array $options)
            ->add('password', 'password')

At this moment, we need to configure our security in app/config/security.yml

      Symfony\Component\Security\Core\User\User: plaintext
      Custom\BookBundle\Entity\User: bcrypt
          providers: [in_memory, user_db]
            admin: {password: adminpass, roles: ROLE_ADMIN}
        entity: {class: CustomBookBundle:User, property: username}
        pattern: /.*
          login_path: /login
          check_path: /login_check
          default_target_path: /book
          path: /logout
          target: /book
        security: true
        anonymous: true

      - { path: /login, roles: [IS_AUTHENTICATED_ANONYMOUSLY, ROLE_USER] }
      - { path: /user/edit, roles: ROLE_ADMIN }
      - { path: /user/index, roles: ROLE_ADMIN }
      - { path: /user/show, roles: ROLE_ADMIN }
      - { path: /user/new, roles: IS_AUTHENTICATED_ANONYMOUSLY }
      - { path: /.*, roles: [IS_AUTHENTICATED_ANONYMOUSLY, ROLE_USER] }

If you check carefully, in line 4 we have added bcrypt, so that the password can be hashed.

Rest of the code is same, until line 33. We have added some more access control for our admin and anonymous user.

Again we need to change our navbar, a little bit to check the user access. So open
app/Resources/views/base.html.twig and edit.

<div id="navbar" class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a href="{{ path('book') }}">Home</a></li>

                    {% if is_granted('ROLE_ADMIN') %}
                        <li><a href="{{ path('logout') }}">Logout</a></li>
                        <li><a href="{{ path('user') }}">User</a></li>
                    {% elseif is_granted('ROLE_USER') %}
                        <li><a href="{{ path('logout') }}">Logout</a></li>
                    {% else %}
                        <li><a href="{{ path('login') }}">Login</a></li>
                        <li><a href="{{ path('user_new') }}">Register</a></li>
                    {% endif %}

We need to delete some code from src/Custom/BookBundle/Resources/views/User/new.html.twig as we don’t want, the user will see the user list.

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

{% block body -%}
    <h1>User creation</h1>

    {{ form(form) }}

{% endblock %}

We are almost done. After register we need to redirect our user to login page. So open src/Custom/BookBundle/Controller/UserController.php and change the login path in line 12.

public function createAction(Request $request)
        $entity = new User();
        $form = $this->createCreateForm($entity);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            return $this->redirect($this->generateUrl('login'));

        return $this->render('CustomBookBundle:User:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),

Yes we are all done. Now open your browser and try to register and login –


Register —


User control by admin —

User Control

By the way, you can download all the code from my –

Happy coding… 🙂

User registration with Symfony

5 comments to “User registration with Symfony”
  1. Can you help me, thanks

    I found this error:
    An exception has been thrown during the rendering of a template (“Unable to generate a URL for the named route “login” as such route does not exist.”) in ::base.html.twig at line 11.

Leave a Reply

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