Solved: Symfony2 + FOSUserBundle use email as username (Outdated)

Note: This article is outdated and only works with 2.1 versions, no update yet.

Today I came across the challenge of removing the username field from FOSUserBundle and found a nice and clean solution based on events.

Because the username field is defined in the base class provided by the bundle, it is not so easy to remove it. Through google I discovered some approaches that would involve changing the handler, the validation rules and so on. The all seemed not so clean to me, so I tried to find a better solution.

My idea was to just use the users email as username. On Stackoverflow someone suggested to change the setter method in the user entity like the following:

This approach is very unclean as well, because the setEmail method has a side effect on the username property.

Due to the fact that I had a custom registration form anyway, I played around with form events and managed to get this to work:

So what I do is, when the data is getting bound to the user entity, the email property is just transferred to the username property before the validation process is started. No side effects and minimal code changes.

4 thoughts on “Solved: Symfony2 + FOSUserBundle use email as username (Outdated)

  1. What happens if the user changes their email address? Does their username get the new email address? What if they then register again with the old email address?

  2. Heya,

    i’ve been trying the same modification to my project. but the snippet you provided didn’t pass the forms validation.
    looks like there’ve been some changes in the internal API, the BIND event got deprecated recently.. maybe you want to check your implementation with recent versions of sf2.3 and FOS?


Leave a Reply

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