This course is archived!
My Users don't have a Username!
Okay: a challenge! In some apps... you don't even need a username - you register and login entirely with your email.
But... with FOSUserBundle, we always have a username field. So, are we stuck?
Nope! It is true that you can't remove the username
field from your user
table.
But, we can remove it from everywhere else.
Auto-Setting the Username Field
Start in the User
class. I'll go to the Code->Generate menu - or Command+N on a
Mac - go to "Override Methods" and choose setEmail()
. Before the parent call,
add $this->setUsername($email)
.
// ... lines 2 - 11 | |
class User extends BaseUser | |
{ | |
// ... lines 14 - 40 | |
/** | |
* Overridden so that username is now optional | |
* | |
* @param string $email | |
* @return User | |
*/ | |
public function setEmail($email) | |
{ | |
$this->setUsername($email); | |
return parent::setEmail($email); | |
} | |
} |
This is big! Thanks to this, we no longer need to worry about ever setting the
username
field. In the database, username
will always equal the email
... which
is definitely redundant and unnecessary, but in practice, it works fine.
Removing the Username Field from the Form
The only other thing we need to do is remove the username
field from the registration
form. How? Easy: in RegistrationFormType
, add ->remove('username')
.
// ... lines 2 - 8 | |
class RegistrationFormType extends AbstractType | |
// ... line 10 | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
$builder | |
->add('firstName') | |
->remove('username'); | |
} | |
// ... lines 17 - 21 | |
} |
Then, in the template, remove its form_row()
.
// ... lines 1 - 2 | |
<h1>Register Aquanaut!</h1> | |
// ... line 4 | |
{{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register'), 'attr': {'class': 'fos_user_registration_register'}}) }} | |
{{ form_row(form.email) }} | |
{{ form_row(form.firstName) }} | |
{{ form_row(form.plainPassword) }} | |
// ... lines 9 - 11 | |
{{ form_end(form) }} |
And yea, that's it! Refresh! No more username! Register as aquanaut4@gmail.com
and submit. Check it out in the database:
php bin/console doctrine:query:sql 'SELECT * FROM user'
There it is! The username
is now equal to the email.
Oh, and if you're using the profile edit page from the bundle, you'll also want to
remove the username
field from the ProfileFormType
form. It's done in exactly
the same way.
Very useful, thank you for this!