Symfony
sponsored by SensioLabs
Menu
  • About
  • Documentation
  • Screencasts
  • Cloud
  • Certification
  • Community
  • Businesses
  • News
  • Download
  1. Home
  2. Documentation
  3. Doctrine
  4. How to Implement a Simple Registration Form
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud
Search by Algolia

Table of Contents

  • Create a Form for the Entity
  • Handling the Form Submission
  • Update your Database Schema
  • Having a Registration form with only Email (no Username)
  • Adding a "accept terms" Checkbox

How to Implement a Simple Registration Form

Edit this page

Warning: You are browsing the documentation for Symfony 2.7, which is no longer maintained.

Read the updated version of this page for Symfony 6.2 (the current stable version).

How to Implement a Simple Registration Form

Creating a registration form is pretty easy - it really means just creating a form that will update some User model object (a Doctrine entity in this example) and then save it.

Tip

The popular FOSUserBundle provides a registration form, reset password form and other user management functionality.

If you don't already have a User entity and a working login system, first start with How to Load Security Users from the Database (the Entity Provider).

Your User entity will probably at least have the following fields:

username
This will be used for logging in, unless you instead want your user to login via email (in that case, this field is unnecessary).
email
A nice piece of information to collect. You can also allow users to login via email.
password
The encoded password.
plainPassword
This field is not persisted: (notice no @ORM\Column above it). It temporarily stores the plain password from the registration form. This field can be validated and is then used to populate the password field.

With some validation added, your class may look something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity
 * @UniqueEntity(fields="email", message="Email already taken")
 * @UniqueEntity(fields="username", message="Username already taken")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255, unique=true)
     * @Assert\NotBlank()
     * @Assert\Email()
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255, unique=true)
     * @Assert\NotBlank()
     */
    private $username;

    /**
     * @Assert\NotBlank()
     * @Assert\Length(max=4096)
     */
    private $plainPassword;

    /**
     * The below length depends on the "algorithm" you use for encoding
     * the password, but this works well with bcrypt.
     *
     * @ORM\Column(type="string", length=64)
     */
    private $password;
    
    /**
     * @ORM\Column(type="array")
     */
    private $roles;

    public function __construct() {
        $this->roles = array('ROLE_USER');
    }

    // other properties and methods

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }

    public function getPlainPassword()
    {
        return $this->plainPassword;
    }

    public function setPlainPassword($password)
    {
        $this->plainPassword = $password;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }

    public function getSalt()
    {
        // The bcrypt algorithm doesn't require a separate salt.
        // You *may* need a real salt if you choose a different encoder.
        return null;
    }
    
    public function getRoles()
    {
        return $this->roles;
    }

    public function eraseCredentials()
    {
    }
}

The UserInterface requires a few other methods and your security.yml file needs to be configured properly to work with the User entity. For a more complete example, see the Entity Provider article.

Why the 4096 Password Limit?

Notice that the plainPassword field has a max length of 4096 characters. For security purposes (CVE-2013-5750), Symfony limits the plain password length to 4096 characters when encoding it. Adding this constraint makes sure that your form will give a validation error if anyone tries a super-long password.

You'll need to add this constraint anywhere in your application where your user submits a plaintext password (e.g. change password form). The only place where you don't need to worry about this is your login form, since Symfony's Security component handles this for you.

Create a Form for the Entity

Next, create the form for the User entity:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// src/AppBundle/Form/UserType.php
namespace AppBundle\Form;

use AppBundle\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', 'email')
            ->add('username', 'text')
            ->add('plainPassword', 'repeated', array(
                'type' => 'password',
                'first_options'  => array('label' => 'Password'),
                'second_options' => array('label' => 'Repeat Password'),
            ))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => User::class,
        ));
    }

    public function getName()
    {
        return 'user';
    }
}

There are just three fields: email, username and plainPassword (repeated to confirm the entered password).

Tip

To explore more things about the Form component, read the Forms guide.

Handling the Form Submission

Next, you need a controller to handle the form rendering and submission. If the form is submitted, the controller performs the validation and saves the data into the database:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// src/AppBundle/Controller/RegistrationController.php
namespace AppBundle\Controller;

use AppBundle\Form\UserType;
use AppBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class RegistrationController extends Controller
{
    /**
     * @Route("/register", name="user_registration")
     */
    public function registerAction(Request $request)
    {
        // 1) build the form
        $user = new User();
        $form = $this->createForm(new UserType(), $user);

        // 2) handle the submit (will only happen on POST)
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            // 3) Encode the password (you could also do this via Doctrine listener)
            $password = $this->get('security.password_encoder')
                ->encodePassword($user, $user->getPlainPassword());
            $user->setPassword($password);

            // 4) save the User!
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();

            // ... do any other work - like sending them an email, etc
            // maybe set a "flash" success message for the user

            return $this->redirectToRoute('replace_with_some_route');
        }

        return $this->render(
            'registration/register.html.twig',
            array('form' => $form->createView())
        );
    }
}

To define the algorithm used to encode the password in step 3 configure the encoder in the security configuration:

  • YAML
  • XML
  • PHP
1
2
3
4
# app/config/security.yml
security:
    encoders:
        AppBundle\Entity\User: bcrypt
1
2
3
4
5
6
7
8
9
10
11
<!-- app/config/security.xml -->
<?xml version="1.0" charset="UTF-8" ?>
<srv:container xmlns="http://symfony.com/schema/dic/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:srv="http://symfony.com/schema/dic/services"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <config>
        <encoder class="AppBundle\Entity\User">bcrypt</encoder>
    </config>
</srv:container>
1
2
3
4
5
6
7
8
// app/config/security.php
use AppBundle\Entity\User;

$container->loadFromExtension('security', array(
    'encoders' => array(
        User::class => 'bcrypt',
    ),
));

In this case the recommended bcrypt algorithm is used. If needed, check out the user password encoding article.

Note

If you decide to NOT use annotation routing (shown above), then you'll need to create a route to this controller:

  • YAML
  • XML
  • PHP
1
2
3
4
# app/config/routing.yml
user_registration:
    path:     /register
    defaults: { _controller: AppBundle:Registration:register }
1
2
3
4
5
6
7
8
9
10
<!-- app/config/routing.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">

    <route id="user_registration" path="/register">
        <default key="_controller">AppBundle:Registration:register</default>
    </route>
</routes>
1
2
3
4
5
6
7
8
9
10
// app/config/routing.php
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;

$routes = new RouteCollection();
$routes->add('user_registration', new Route('/register', array(
    '_controller' => 'AppBundle:Registration:register',
)));

return $routes;

Next, create the template:

  • Twig
  • PHP
1
2
3
4
5
6
7
8
9
10
{# app/Resources/views/registration/register.html.twig #}

{{ form_start(form) }}
    {{ form_row(form.username) }}
    {{ form_row(form.email) }}
    {{ form_row(form.plainPassword.first) }}
    {{ form_row(form.plainPassword.second) }}

    <button type="submit">Register!</button>
{{ form_end(form) }}
1
2
3
4
5
6
7
8
9
10
11
<!-- app/Resources/views/registration/register.html.php -->

<?php echo $view['form']->start($form) ?>
    <?php echo $view['form']->row($form['username']) ?>
    <?php echo $view['form']->row($form['email']) ?>

    <?php echo $view['form']->row($form['plainPassword']['first']) ?>
    <?php echo $view['form']->row($form['plainPassword']['second']) ?>

    <button type="submit">Register!</button>
<?php echo $view['form']->end($form) ?>

See How to Customize Form Rendering for more details.

Update your Database Schema

If you've updated the User entity during this tutorial, you have to update your database schema using this command:

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

That's it! Head to /register to try things out!

Having a Registration form with only Email (no Username)

If you want your users to login via email and you don't need a username, then you can remove it from your User entity entirely. Instead, make getUsername() return the email property:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/AppBundle/Entity/User.php
// ...

class User implements UserInterface
{
    // ...

    public function getUsername()
    {
        return $this->email;
    }

    // ...
}

Next, just update the providers section of your security.yml file so that Symfony knows how to load your users via the email property on login. See How to Load Security Users from the Database (the Entity Provider).

Adding a "accept terms" Checkbox

Sometimes, you want a "Do you accept the terms and conditions" checkbox on your registration form. The only trick is that you want to add this field to your form without adding an unnecessary new termsAccepted property to your User entity that you'll never need.

To do this, add a termsAccepted field to your form, but set its mapped option to false:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/AppBundle/Form/UserType.php
// ...
use Symfony\Component\Validator\Constraints\IsTrue;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', 'email');
            // ...
            ->add('termsAccepted', 'checkbox', array(
                'mapped' => false,
                'constraints' => new IsTrue(),
            ))
        );
    }
}

The constraints option is also used, which allows us to add validation, even though there is no termsAccepted property on User.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
We stand with Ukraine.
Version:
Code consumes server resources. Blackfire tells you how

Code consumes server resources. Blackfire tells you how

Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

Be trained by SensioLabs experts (2 to 6 day sessions -- French or English).

↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

Avatar of Peter Schultz, a Symfony contributor

Thanks Peter Schultz for being a Symfony contributor

2 commits • 34 lines changed

View all contributors that help us make Symfony

Become a Symfony contributor

Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

Learn how to contribute

Symfony™ is a trademark of Symfony SAS. All rights reserved.

  • What is Symfony?
    • Symfony at a Glance
    • Symfony Components
    • Case Studies
    • Symfony Releases
    • Security Policy
    • Logo & Screenshots
    • Trademark & Licenses
    • symfony1 Legacy
  • Learn Symfony
    • Symfony Docs
    • Symfony Book
    • Reference
    • Bundles
    • Best Practices
    • Training
    • eLearning Platform
    • Certification
  • Screencasts
    • Learn Symfony
    • Learn PHP
    • Learn JavaScript
    • Learn Drupal
    • Learn RESTful APIs
  • Community
    • SymfonyConnect
    • Support
    • How to be Involved
    • Code of Conduct
    • Events & Meetups
    • Projects using Symfony
    • Downloads Stats
    • Contributors
    • Backers
  • Blog
    • Events & Meetups
    • A week of symfony
    • Case studies
    • Cloud
    • Community
    • Conferences
    • Diversity
    • Documentation
    • Living on the edge
    • Releases
    • Security Advisories
    • SymfonyInsight
    • Twig
    • SensioLabs
  • Services
    • SensioLabs services
    • Train developers
    • Manage your project quality
    • Improve your project performance
    • Host Symfony projects
    Deployed on
Follow Symfony
Search by Algolia