我是 Yii 的初学者,这就是为什么无法弄清楚,出了什么问题。 我使用相同的模型 - 用户 - 进行登录、注册和版本配置文件。
用户模型:
class Users extends \yii\db\ActiveRecord {
public $password_repeat; //have no this value in DB, that's why write it as property directly. Need only for profile editing
public function rules() {
return [
[['username', 'password', 'authKey', 'accessToken'], 'safe'],
[['username', 'password'], 'required'],
[['username', 'password', 'authKey', 'accessToken'], 'string', 'max' => 255],
[['is_admin'], 'boolean'],
//don't use scenarios() here. Use 'on' instead
['password_repeat', 'required', 'on' => 'update'],
['password_repeat', 'compare', 'compareAttribute'=>'password', 'message'=>"Passwords don't match", 'on' => 'update' ],
];
}
}
查看代码片段:
<?php $form = ActiveForm::begin([
'id' => 'data-form',
'options' => ['class' => 'form-horizontal', 'enctype' => 'multipart/form-data'],
'fieldConfig' => [
'template' => "{label}\n<div class=\"col-lg-3\">{input}</div>\n<div class=\"col-lg-6\">{error}</div>",
'labelOptions' => ['class' => 'col-lg-1 control-label'],
],
]); ?>
<?= $form->field($user_data, 'username') ?>
<?= $form->field($logo_data, 'imageFile')->fileInput() ?>
<?= $form->field($user_data, 'password')->passwordInput(['value'=>''])?>
<?= $form->field($user_data, 'password_repeat')->passwordInput(['value'=>''])?>
<?= Html::submitButton('Zapisz', ['class' => 'btn btn-primary btn-block', 'name' => 'data-button']) ?>
<?php ActiveForm::end(); ?>
站点 Controller 操作:
public function actionProfile(){
//3 model instances to retrieve data from users && company_profiles and logo
$user_data = Users::find()->where(['id'=>Yii::$app->user->id])->one();
$company_profile_data = CompanyProfiles::find()->where(['user_id'=>Yii::$app->user->id])->one();
$logo_data = new UploadLogo();
//here I upload file through $logo_data
if (isset($_POST['Users'])){
$user_data->username = $_POST['Users']['username'];
$company_profile_data->firm_data = $_POST['CompanyProfiles']['firm_data'];
//other assignments
$user_data->scenario = 'update'; //specially for 'profile' page
if (($_POST[Users][password] !== '') && ($_POST[Users][password_repeat]) !== '' && ($_POST[Users][password] == $_POST[Users][password_repeat]))
$user_data->password_repeat = $user_data->password = md5($_POST[Users][password]); //MAYBE, problem is here?
$user_data->update();
$company_profile_data->update();
}
return $this->render('profile', ['user_data' => $user_data, 'company_profile_data' => $company_profile_data, 'logo_data' => $logo_data]);
}
我使用更新场景来进行个人资料编辑页面。在这种情况下,需要使用password_repeat,并且需要与密码相同。但它并没有按预期工作。 答:当我尝试在未输入密码的情况下提交表单并重新传递时,我仅看到密码“不能为空”消息。然后我将值放入 ONLY pass 输入中,然后页面重新加载(数据库表不会更改),重新加载后我看到消息“不能为空”,这次是重新传递字段!但最奇怪的是,在下一页重新加载之前一切正常。重新加载后转到A;:) 如果我删除场景,验证一切正常。但我无法删除它,因为在这种情况下注册失败(需要填写重新传递字段)。
那么,我需要如何使用传递-重传递功能才能正常工作(使用场景“更新”)?哪里出错了?
最佳答案
明白了!我只需要移动这个代码行:
$user_data->scenario = 'update';
来自IF stmt。现在我想养成一个习惯,直接在创建模型实例时分配场景属性。
关于php - Yii2:比较密码和重设密码的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31730011/