1
0

SignupForm.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace frontend\models;
  3. use yii\base\Model;
  4. use common\models\User;
  5. /**
  6. * Signup form
  7. */
  8. class SignupForm extends Model
  9. {
  10. public $username;
  11. public $email;
  12. public $password;
  13. /**
  14. * @inheritdoc
  15. */
  16. public function rules()
  17. {
  18. return [
  19. ['username', 'trim'],
  20. ['username', 'required'],
  21. ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
  22. ['username', 'string', 'min' => 2, 'max' => 255],
  23. ['email', 'trim'],
  24. ['email', 'required'],
  25. ['email', 'email'],
  26. ['email', 'string', 'max' => 255],
  27. ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
  28. ['password', 'required'],
  29. ['password', 'string', 'min' => 6],
  30. ];
  31. }
  32. /**
  33. * Signs user up.
  34. *
  35. * @return User|null the saved model or null if saving fails
  36. */
  37. public function signup()
  38. {
  39. if (!$this->validate()) {
  40. return null;
  41. }
  42. $user = new User();
  43. $user->username = $this->username;
  44. $user->email = $this->email;
  45. $user->setPassword($this->password);
  46. $user->generateAuthKey();
  47. return $user->save() ? $user : null;
  48. }
  49. }