RosS
RosS

Reputation: 317

Logging with Email and Password , Not with Username Yii 2

How I can manage to login with email address,not with the standart (username + password).I enter the website with my Users in my DataBase , but is there a way to change that to be with email address instead of that user name , because when I use Gii , I got a lot of errors , even I try to fix those errors

Upvotes: 0

Views: 1806

Answers (2)

RosS
RosS

Reputation: 317

I made it just change everywhere where must be email,instead of username,because of Yii default username loggin , thank u for the advices

Upvotes: 0

Funso Popoola
Funso Popoola

Reputation: 78

First, try to locate your SiteController or any other Controller you use for the index route. It should have an action function that corresponds to the login route; it is usually with signature public function actionLogin().

You should see the initialized model (usually, the LoginForm model). The model should have a function for login logic which is checked to determine user authenticity. You should find that this function invokes another login function which requires the User object as first argument/parameter. The function is usually the $this->getUser() function.

Looking into this will point to you a call to the actual data model that fetches user by whatever criteria/property you specify; this can be email or anything else that might not even need be unique but generally, you want to use a unique data property like username and email. This function relies on the User data model. It, by Gii default, calls the function User::findByUsername(search_property)

Yii2 provides a default User model that implements the Identity interface; that's where you want to make the adjustment you need. It should have the required static function findByUsername() or something similar. You would find that Yii2 default searches within static data to find user, you should link that to you (User) data model which I assume you generated using Gii.

My Gii sequence usually looks like such:

  1. List item
  2. Generate the yii2-basic/yii2-advanced using composer
  3. Create Database (I have a user table in there) and set proper db credentials in config/db.php
  4. Rename the default model/User.php to model/OldUser.php
  5. Create Data Models using Gii
  6. Make the newly generated User Model implement IdentityInterface to allow Yii2 freely-given session management by adding implements yii\web\IdentityInterface to the class declaration.
  7. Implement all the required methods of the IdentityInterface. You can check in `model/OldUser.php' for guidance.
  8. Create static functions to findUserByEmail($email) or findUserByUsername($username)

Mine usually look like this

I hope this helps.

Upvotes: 5

Related Questions