我在我的 Yii Web 应用程序中使用来自 Dektrium 的 SettingsForm 模型进行用户配置文件设置。在此模型中,每当用户想要更新其个人资料时,都需要输入当前密码 (current_password)。但是,我只想在用户打算更改密码时才需要 current_password (在“new_password”字段中插入新值;否则,对于其他配置文件更改来说不应该是强制的。 如何在不更改库模型SettingsForm的情况下实现这一目标?
这是我的代码相关部分的片段:
/**
* SettingsForm gets user's username, email and password and changes them.
*
* @property User $user
*
* @author Dmitry Erofeev <[email protected]>
*/
class SettingsForm extends Model
{
/** @var string */
public $new_password;
/** @var string */
public $current_password;
/** @inheritdoc */
public function rules()
{
return [
'newPasswordLength' => ['new_password', 'string', 'max' => 72, 'min' => 6],
'currentPasswordRequired' => ['current_password', 'required'],
'currentPasswordValidate' => ['current_password', function ($attr) {
if (!Password::validate($this->$attr, $this->user->password_hash)) {
$this->addError($attr, Yii::t('user', 'Current password is not valid'));
}
}],
];
}
这是控制器中的操作
public function actionAccount()
{
/** @var SettingsForm $model */
$model = \Yii::createObject(SettingsForm::className());
$profile = Profile::find()->where(['user_id' => Yii::$app->user->identity->getId()])->one();
$event = $this->getFormEvent($model);
$this->performAjaxValidation($model);
$old_attachs = [];
$files_preview = [];
if ($profile->gravatar_id) {
$old_attachs = $profile->getImageUrl();
$files_preview = $profile->getImagePreview();
}
$this->trigger(self::EVENT_BEFORE_ACCOUNT_UPDATE, $event);
if ($model->load(\Yii::$app->request->post()) && $model->save()) {
\Yii::$app->session->setFlash('success', \Yii::t('user', 'Your account details have been updated'));
$this->trigger(self::EVENT_AFTER_ACCOUNT_UPDATE, $event);
if ($profile->load(\Yii::$app->request->post())) $profile->save();
$profile->avatarFile = UploadedFile::getInstance($profile, 'avatarFile');
$profile->upload();
return $this->refresh();
}
return $this->render('@app/views/my-settings/account', [
'model' => $model,
'profile' => $profile,
'old_attachs' => $old_attachs,
'files_preview' => $files_preview,
]);
}
最后视图内的字段是
<?php echo $form->field($model, 'new_password')->passwordInput() ?>
<?php echo $form->field($model, 'current_password')->passwordInput() ?>
可以使用条件验证来制作Yii 文档:
['old_password', 'required', 'when' => function($model) {
return $model->new_password != '';
}]