Yii2创建或更新用户个人资料

时间:2018-09-20 18:48:32

标签: yii2 crud yii2-basic-app

在我的基本应用程序中,我有一个User模型和一个UserForm模型,用于存储和更新数据库中的用户。现在,更新用户个人资料时出现问题。它反馈“成功更新!”即使新数据无法保存。

我的桌子:

Table name: User
Attributes: id, fname, mname, lname, address, username, auth_key, password_hash, password_reset_token, email, status, created_at, updated_at

我的模特:

class UserForm extends Model
{
    public $fname;
    public $mname;
    public $lname;
    public $address;
    public $username;
    public $email;
    public $password_hash;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['fname', 'required'],
            ['fname', 'trim'],

            ['mname', 'trim'],

            ['lname', 'required'],
            ['lname', 'trim'],

            ['address', 'required'],
            ['address', 'trim'],
            ['address', 'string', 'max' => 255],

            ['username', 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\app\models\User', 'message' => 'This username has already been taken.'],
            ['username', 'string', 'min' => 4, 'max' => 255],   

            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'This email address has already been taken.'],

            ['password_hash', 'required', 'on' => 'insert'],
            ['password_hash', 'string', 'min' => 8],
        ];
    }

    public function beforeSave($insert) {
        if ($insert) {
            $this->setPassword($this->password_hash);
        } else {
            if (!empty($this->password_hash)) {
                $this->setPassword($this->password_hash);
            } else {
                $this->password_hash = (string) $this->getOldAttribute('password_hash');
            }
        }
        return parent::beforeSave($insert);
    }
}

我的控制器:

public function actionUpdate($id)
{
    $model = $this->findModel($id);
    $model->setAttribute('password_hash', null);

    if ($model->load(Yii::$app->request->post()) && $model->save()) {
        Yii::$app->session->setFlash('success', Yii::t('app', 'Successful update!'));            
        return $this->redirect(['overview']);
    } else {
        return $this->render('update', [
            'model' => $model,
        ]);
    }
}

protected function findModel($id) {
    if (($model = User::findOne($id)) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

我的view.php     

    <?= $form->field($model, 'fname')->textInput(['autofocus' => true])->label('First Name') ?>
    <?= $form->field($model, 'mname')->textInput()->label('Middle Name') ?>
    <?= $form->field($model, 'lname')->textInput()->label('Last Name') ?>
    <?= $form->field($model, 'address')->textInput() ?>
    <?= $form->field($model, 'username')->textInput() ?>
    <?= $form->field($model, 'email') ?>
    <?= $form->field($model, 'password_hash')->passwordInput(['placeholder' => Yii::t('app', 'Password'), 'value' => ''])->label(false) ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

<?php ActiveForm::end(); ?>

其中一些步骤来自此处:yii2 user CRUD create or update with password

1 个答案:

答案 0 :(得分:1)

您的UserForm从未使用过。您的findModel()返回User,因此所有验证和保存均由User模型处理-我猜它没有任何验证规则,因此$model->load()不加载任何内容。 / p>

您可以尝试从活动记录模型扩展表单模型:

class UserForm extends User

并在findModel()中使用它或创建用于返回表单模型的单独方法:

protected function findFormModel($id) {
    if (($model = UserForm::findOne($id)) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

然后在您的update操作中使用此方法。不要忘记从UserForm中删除旧属性-它们是不必要的,并且可能会破坏属性行为。