我是Yii的初学者,这就是为什么不能弄清楚,哪里出错了。我使用相同的模型- Users -登录,注册和版本配置文件。
用户模型:
class Users extends yiidbActiveRecord {
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' ],
];
}
}
<<p> 视图片段/em>: <?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(); ?>
站点控制器动作:
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是必需的,并且需要与password相同。但它并没有像预期的那样工作。A:当我尝试提交表单没有输入密码和重新通过,我看到消息"不能是空白"只有密码。然后我把值只传递输入,页面重新加载(DB表不改变),重新加载后,我看到消息"不能是空白"这一次为重传字段!但最奇怪的是,在下一个页面重新加载之前,一切工作正常。重新加载后转到A;:)如果我删除场景,一切都可以验证。但是我不能删除它,因为在这种情况下注册失败(repass字段需要填写)。
所以,我需要做我的传递-重传功能工作它很好(与场景'更新')?错误在哪里?
明白了!我只需要移动这个代码线:
$user_data->scenario = 'update';
from IF现在我想养成一个习惯,直接在创建模型实例下分配场景属性。