我有注册表格,注册新用户。但是当我输入数据时,所有字段都会在DB中保存一个(用户名)。我无法理解为什么。帮助我。
这是来自SignupForm的代码
<?php
namespace app\modules\user\models;
use yii\base\Model;
use Yii;
/**
* Signup form
*/
class SignupForm extends Model
{
public $username;
public $email;
public $password;
public $verifyCode;
public function rules()
{
return [
['username', 'filter', 'filter' => 'trim'],
['username', 'required'],
['username', 'match', 'pattern' => '#^[\w_-]+$#i'],
['username', 'unique', 'targetClass' => User::className(), 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'filter', 'filter' => 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'unique', 'targetClass' => User::className(), 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
['verifyCode', 'captcha', 'captchaAction' => '/user/default/captcha'],
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'username' => Yii::t('app', 'USER_USERNAME'),
'email' => Yii::t('app', 'USER_EMAIL'),
'password' => Yii::t('app', 'USER_PASSWORD'),
'verifyCode' => Yii::t('app', 'USER_VERIFYCODE'),
];
}
/**
* Signs user up.
*
* @return User|null the saved model or null if saving fails
*/
public function signup()
{
if ($this->validate()) {
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->status = User::STATUS_WAIT;
$user->generateAuthKey();
$user->generateEmailConfirmToken();
if ($user->save()) {
Yii::$app->mailer->compose('@app/modules/user/mails/emailConfirm', ['user' => $user])
->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name])
->setTo($this->email)
->setSubject('Email confirmation for ' . Yii::$app->name)
->send();
}
return $user;
}
return null;
}
}
注册代码(查看)
<?php
use yii\captcha\Captcha;
use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model app\modules\user\models\SignupForm */
$this->title = Yii::t('app', 'TITLE_SIGNUP');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-default-signup">
<h1><?= Yii::t('app', 'TITLE_SIGNUP') ?></h1>
<p>Please fill out the following fields to signup:</p>
<div class="row">
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>
<?= $form->field($model, 'username') -> textInput() ?>
<?= $form->field($model, 'email') -> textInput() ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className(), [
'captchaAction' => '/user/default/captcha',
'template' => '<div class="row"><div class="col-lg-3">{image}</div><div class="col-lg-6">{input}</div></div>',
]) ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
来自DefaultController的代码
...
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
Yii::$app->getSession()->setFlash('success', 'Подтвердите ваш электронный адрес.');
return $this->goHome();
}
}
return $this->render('signup', [
'model' => $model,
]);
}
...
来自用户(模型)的代码
<?php
namespace app\modules\user\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\web\IdentityInterface;
/**
* This is the model class for table "{{%user}}".
*
* @property integer $id
* @property integer $created_at
* @property integer $updated_at
* @property string $username
* @property string $auth_key
* @property string $email_confirm_token
* @property string $password_hash
* @property string $password_reset_token
* @property string $email
* @property integer $status
*/
class User extends ActiveRecord implements IdentityInterface
{
const SCENARIO_PROFILE = 'profile';
const STATUS_BLOCKED = 0;
const STATUS_ACTIVE = 1;
const STATUS_WAIT = 2;
public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public function rules()
{
return [
['username', 'required'],
['username', 'match', 'pattern' => '#^[\w_-]+$#i'],
['username', 'unique', 'targetClass' => self::className(), 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 255],
['email', 'required', 'except' => self::SCENARIO_PROFILE],
['email', 'email', 'except' => self::SCENARIO_PROFILE],
['email', 'unique', 'targetClass' => self::className(), 'except' => self::SCENARIO_PROFILE, 'message' => Yii::t('app', 'ERROR_EMAIL_EXISTS')],
['email', 'string', 'max' => 255, 'except' => self::SCENARIO_PROFILE],
['status', 'integer'],
['status', 'default', 'value' => self::STATUS_ACTIVE],
['status', 'in', 'range' => array_keys(self::getStatusesArray())],
];
}
public function attributeLabels()
{
return [
'id' => 'ID',
'created_at' => Yii::t('app', 'USER_CREATED'), //'Создан',
'updated_at' => Yii::t('app', 'USER_UPDATE'), //'Обновлён',
'username' => Yii::t('app', 'USER_USERNAME'), // 'Имя пользователя',
'email' => Yii::t('app', 'USER_EMAIL'), // 'Email',
'status' => Yii::t('app', 'USER_STATUS'), //'Статус',
];
}
public function scenarios()
{
return [
self::SCENARIO_DEFAULT => ['username', 'email', 'status'],
self::SCENARIO_PROFILE => ['email'],
];
}
public function behaviors()
{
return [
TimestampBehavior::className(),
];
}
/**
* @inheritdoc
*/
public static function findIdentity($id)
{
return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
}
/**
* @inheritdoc
*/
public static function findIdentityByAccessToken($token, $type = null)
{
throw new NotSupportedException('findIdentityByAccessToken is not implemented.');
}
/**
* Finds user by username
*
* @param string $username
* @return static|null
*/
public static function findByUsername($username)
{
return static::findOne(['username' => $username]);
}
/**
* @inheritdoc
*/
public function getId()
{
return $this->getPrimaryKey();
}
/**
* @inheritdoc
*/
public function getAuthKey()
{
return $this->auth_key;
}
/**
* @inheritdoc
*/
public function validateAuthKey($authKey)
{
return $this->getAuthKey() === $authKey;
}
/**
* Validates password
*
* @param string $password password to validate
* @return boolean if password provided is valid for current user
*/
public function validatePassword($password)
{
return Yii::$app->security->validatePassword($password, $this->password_hash);
}
public function getStatusName()
{
return ArrayHelper::getValue(self::getStatusesArray(), $this->status);
}
public static function getStatusesArray()
{
return [
self::STATUS_BLOCKED => 'Заблокирован',
self::STATUS_ACTIVE => 'Активен',
self::STATUS_WAIT => 'Ожидает подтверждения',
];
}
/**
* @param string $password
*/
public function setPassword($password)
{
$this->password_hash = Yii::$app->security->generatePasswordHash($password);
}
/**
* Generates "remember me" authentication key
*/
public function generateAuthKey()
{
$this->auth_key = Yii::$app->security->generateRandomString();
}
public function beforeSave($insert)
{
if (parent::beforeSave($insert)) {
if ($insert) {
$this->generateAuthKey();
}
return true;
}
return false;
}
//************************************
/**
* Finds user by password reset token
*
* @param string $token password reset token
* @return static|null
*/
public static function findByPasswordResetToken($token)
{
if (!static::isPasswordResetTokenValid($token)) {
return null;
}
return static::findOne([
'password_reset_token' => $token,
'status' => self::STATUS_ACTIVE,
]);
}
/**
* Finds out if password reset token is valid
*
* @param string $token password reset token
* @return boolean
*/
public static function isPasswordResetTokenValid($token)
{
if (empty($token)) {
return false;
}
$expire = Yii::$app->params['user.passwordResetTokenExpire'];
$parts = explode('_', $token);
$timestamp = (int) end($parts);
return $timestamp + $expire >= time();
}
/**
* Generates new password reset token
*/
public function generatePasswordResetToken()
{
$this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
}
/**
* Removes password reset token
*/
public function removePasswordResetToken()
{
$this->password_reset_token = null;
}
//************************************
/**
* @param string $email_confirm_token
* @return static|null
*/
public static function findByEmailConfirmToken($email_confirm_token)
{
return static::findOne(['email_confirm_token' => $email_confirm_token, 'status' => self::STATUS_WAIT]);
}
/**
* Generates email confirmation token
*/
public function generateEmailConfirmToken()
{
$this->email_confirm_token = Yii::$app->security->generateRandomString();
}
/**
* Removes email confirmation token
*/
public function removeEmailConfirmToken()
{
$this->email_confirm_token = null;
}
}
答案 0 :(得分:1)