1
votes

I'm trying to create simple project on Yii2. Now I'm creating User functionality. I already created User model and CRUD with Gii. When I create new user or edit, model saves password in plain text. I want to override this functionality to have an ability to save password for example in md5 format.

In Zend Framework there was similar ability. I have password field and when I want to change default setting password behavior I just created setPassword method in the model. Which way is correct for Yii2?

In my User.php model class I created setPassword($password) method but it is not executed (I check it putting var_dump inside).

2
Check how this is done in Advanced Project Template. - Bizley
I want to understand how it works, I don't need it done, just understand - vitasya

2 Answers

1
votes

Based on the Advanced Project Template:

  1. Model SignupForm is resposible for creating new User model.
  2. Controller running this process is SiteController with action Signup - when SignupForm is properly load()-ed method signup() from SignupForm is called.
  3. When data is properly validated new instance of User class is initialised.
  4. New password is set by calling $user->setPassword($this->password); - $this->password is raw plain text password chosen by user.
  5. Method setPassword() sets password_hash property which is generated (hashed and salted) based on the plain-text password - this hashed password is stored in the database.
  6. You can change the way password is hashed by modifying setPassword() (it's not recommended though).
0
votes

You could implement the beforeSave method see here, and encrypt the password.

Alternatively, you could do this in the controller in the actionCreate method before calling $model->save().