Remove / Replace the username field with email using FOSUserBundle in Symfony2 / Symfony3

Asked
Active3 hr before
Viewed126 times

9 Answers

fieldusingusernamereplaceremove
90%

Meta Stack Overflow ,Stack Overflow en español,Stack Overflow em Português, Stack Overflow Public questions & answers

1. Override setter in Acme\UserBundle\Entity\User

public
function setEmail($email) {
   $email = is_null($email) ? '' : $email;
   parent::setEmail($email);
   $this - > setUsername($email);

   return $this;
}

(in both RegistrationFormType and ProfileFormType)

public
function buildForm(FormBuilder $builder, array $options) {
   parent::buildForm($builder, $options);
   $builder - > remove('username'); // we use email as the username
   //..
}

3.a. Update config file in Acme\UserBundle\Resources\config\config.yml

fos_user:
   db_driver: orm
firewall_name: main
user_class: Acme\ UserBundle\ Entity\ User
registration:
   form:
   type: acme_user_registration
validation_groups: [AcmeRegistration]
profile:
   form:
   type: acme_user_profile
validation_groups: [AcmeProfile]
load more v
88%

Best way to remove usernames from FOSUserBundle,Problem is if the user leaves the email address blank, I get two constraint violations:,But then I am stuck with two constraint violations.,and adjust it to your needs. Change the class name, then add your constraints:

1. Override setter in AcmeUserBundleEntityUser

public
function setEmail($email) {
   $email = is_null($email) ? '' : $email;
   parent::setEmail($email);
   $this - > setUsername($email);

   return $this;
}

(in both RegistrationFormType and ProfileFormType)

public
function buildForm(FormBuilder $builder, array $options) {
   parent::buildForm($builder, $options);
   $builder - > remove('username'); // we use email as the username
   //..
}

3.a. Update config file in AcmeUserBundleResourcesconfigconfig.yml

fos_user:
   db_driver: orm
firewall_name: main
user_class: AcmeUserBundleEntityUser
registration:
   form:
   type: acme_user_registration
validation_groups: [AcmeRegistration]
profile:
   form:
   type: acme_user_profile
validation_groups: [AcmeProfile]
load more v
72%

I want to use email instead of username as the login mode. Is this possible with symfony2 / symfony3 and FOSUserbundle?,I was able to do this by overriding both the registration and the profile form type described in detail here, and deleting the username field.,Now you will not see the username field in the form (thanks $builder->remove('username'); ). and when you submit the form, you will no longer receive the "Please enter username" verification error because it is no longer required (thanks to the annotation).,Thus, the validator will not cause any violations. But be sure to include the email address for the username sent by Patt .

1. Override the installer in Acme\UserBundle\Entity\User

 public
 function setEmail($email) {
    $email = is_null($email) ? '' : $email;
    parent::setEmail($email);
    $this - > setUsername($email);
    return $this;
 }

(both in RegistrationFormType and ProfileFormType )

 public
 function buildForm(FormBuilder $builder, array $options) {
    parent::buildForm($builder, $options);
    $builder - > remove('username'); // we use email as the username //.. } 

3.a. Update the configuration file in Acme\UserBundle\Resources\config\config.yml

 fos_user: db_driver: orm firewall_name: main user_class: Acme\ UserBundle\ Entity\ User registration: form: type: acme_user_registration validation_groups: [AcmeRegistration] profile: form: type: acme_user_profile validation_groups: [AcmeProfile]
load more v
65%

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.,The only other thing we need to do is remove the username field from the registration form. How? Easy: in RegistrationFormType, add ->remove('username')., 07. My Users don't have a Username! 2:22

php bin / console doctrine: query: sql 'SELECT * FROM user'
load more v
75%

By default FOS Users only have username, email, and password attributes. If you want to add more information like an address or phone number to your users there are several steps you’ll need to take which are described here.,To make use of the new form types you will need to add information on them to your configuration files.,Notice how it adds phoneNumber to the FormBuilderInterface instance in buildForm().,This is what your getter and setter will look like for the phoneNumber attribute:

// src/AppBundle/Entity/User.php

namespace AppBundleEntity;

use FOS\ UserBundle\ Model\ User as BaseUser;
use Doctrine\ ORM\ Mapping as ORM;
use Symfony\ Component\ Validator\ Constraints as Assert;

/**
 * @ORMEntity
 * @ORMTable(name="fos_user")
 */
class User extends BaseUser {
   /**
    * @ORMId
    * @ORMColumn(type="integer")
    * @ORMGeneratedValue(strategy="AUTO")
    */
   protected $id;

   /**
    * @ORMColumn(type="string")
    * @AssertNotBlank(message="Please enter your phone number.", groups={"Registration", "Profile"})
    * @AssertLength(
    *     min=7,
    *     max=25,
    *     minMessage="The phone number is too short.",
    *     maxMessage="The phone number is too long.",
    *     groups={"Registration", “Profile”}
    * )
    */
   private $phoneNumber;
load more v
40%

Don't let this controller confuse you. As you'll see in a moment, when the user submits the form, the security system automatically handles the form submission for you. If the user submits an invalid username or password, this controller reads the form submission error from the security system, so that it can be displayed back to the user.,In other words, your job is to display the login form and any login errors that may have occurred, but the security system itself takes care of checking the submitted username and password and authenticating the user.,And that's it! When you submit the form, the security system will automatically check the user's credentials and either authenticate the user or send the user back to the login form where the error can be displayed.,After a failed login (e.g. an invalid username or password was submitted), the user is redirected back to the login form itself. Use the failure_path option to define a new target via a relative/absolute URL or a Symfony route name:

1
2
3
4
5
6
7
8
9
10
11
# config / packages / security.yaml
security:
   #...

   firewalls:
   main:
   anonymous: true
lazy: true
form_login:
   login_path: login
check_path: login
load more v
22%

Is there any way to get FOSUserBundle to register/login by email only and disable/remove the username property?,Override the FormHandler, simply replace process by its own code in FOSUserBundle's equivalent class, but adding the username you want there :,and leave the rest of the method as it is defined in FOSUserBundle RegistrationFormHandler.php,A recent project of mine required exactly what you're trying to do, rather then disabling/removing the username I made it a hidden field that was filled in with a random set of numbers during registration and enabled the email log in functionality found here: https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/logging_by_username_or_email.md.

        $user = $this - > userManager - > createUser(); //Original FOSUser line
        $user - > setUsername(uniqid("u", true)); //Creating my own uid for the username
        $this - > form - > setData($user); //Original FOSUser line
load more v
60%

FOSUserBundle is a preferred choice to create user management(login, register,profile,logout) system in symfony.I have already covered the following topics about FOSUserBundle:,The following is the URL of a live demo of the user management system with several users  and an admin user: ,How To Implement FOSUserBundle In Symfony 3.1,This is a very simple example of how you could easily integrate FOSUserBundle and EasyAdminBundle to create a powerful user management system. If you need help with the code or any other aspect of this Symfony user management system, do leave a comment below.

The first step in the integration is to install EasyAdminBundle and enable it in AppKernel.php file. As always, Composer is the preferred method for installation:

$ composer require javiereguiluz / easyadmin - bundle
load more v
48%

Learn how to configure the HWIOAuthBundle properly with FOSUserBundle in your Symfony 3 project to allow Social Login. ,The first you need to do is to install the HWIOAuthBundle with composer using the following command:,If you set everything in order, you will be able to retrieve those properties from the User object and you can proceed to configure the HWIOAuthBundle.,For more information about how the configuration of every resource owner works, refer to the official docs of HWIOAuthBundle here.

The 2 fields for every resource owners follow the next nomenclature: <social-network-name>_id and <social-network-name>_access_token. For example, with our 4 mentioned social networks we would have 8 new columns in the fos_user table namely:

github_id
github_access_token

facebook
facebook_access_token

googleplus_id
googleplus_access_token

stackexchange_id
stackexchange_access_token
load more v

Other "field-using" queries related to "Remove / Replace the username field with email using FOSUserBundle in Symfony2 / Symfony3"