SignupForm.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. * @inheritdoc
  34. */
  35. public function attributeLabels()
  36. {
  37. return [
  38. 'username' => '验证码',
  39. 'name' => '姓名',
  40. 'email' => '电子邮件',
  41. 'password' => '密码',
  42. 'body' => '内容',
  43. ];
  44. }
  45. /**
  46. * Signs user up.
  47. *
  48. * @return User|null the saved model or null if saving fails
  49. */
  50. public function signup()
  51. {
  52. if (!$this->validate()) {
  53. return null;
  54. }
  55. $user = new User();
  56. $user->username = $this->username;
  57. $user->email = $this->email;
  58. $user->setPassword($this->password);
  59. $user->generateAuthKey();
  60. return $user->save() ? $user : null;
  61. }
  62. }