Today, I was confronted to a tricky problem: identify two different types of user, using the FOSUserBundle of Symfony.

We have two kind of users: “standard” users, and “pro” users (consider them as “admin” or “moderator”). Pro users are standard users having a bigger role and containing more informations (phone number, etc.).

All users logged in with the same form, but if you go to the “Pro” section, your account need to be a “Pro” account.

We use the great FOSUserBundle for Symfony, but the bundle is package to have only one type of user. As you can see in the configuration reference, there is only one fos_user.registration.form.type .

 

Here is how I did the trick

In the app/config/security.yml  of our project:

With this config, all users are considered the same, but standard users and anonymous are redirected on the “Create a pro account” page of the website if they go the the /pro section.

 

We have to override the FOSUserBundle, like defined in this page.

In the previous security.yml , you can see that we defined a  mapado_pro_user_register route. The route is defined like this:

File: src/Mapado/UserBundle/Resources/config/routing/pro-registration.xml  . Watch out, at first, I named it registration.xml , but if you do this, you override the FOSUserBundle registration.xml , and the routes are unavailable (and that’s not what I wanted at all).

Don’t forget to add it in your routing.yml

Now the tricky part

I wanted to use all the FOSUserBunde intelligence (mail, activation, etc.), but I wanted to override the registration form type.

I created my new Form Type:

And a controller:

And the template:

The tricky part is the form handler in the controller: that is where the FOSUserBundle logic is.

They use a service with a lots of dependancy injection, and finally the fos_user.registration.form  (defined in the fos_user  configuration), and that is where we wanted to hook in.

What I did is to create a RegistrationFormType , and create a new RegistrationFormHandler  with it. This way, all the registration logic is kept intact by the FOSUserBundle, but if you go on the /registration  page, you create a standard user, if you go on /pro/registration , you create a “pro” user.