Модель не сохраняется при подтверждении пароля, используемого в Yii2
В моем проекте у меня проблемы с использованием пароля подтверждения.
У меня нет поля подтверждения пароля в моей базе данных, я предполагаю, что именно поэтому я получаю эту ошибку.
Моя модель
public $user_password_hash_repeat;
public $agree;
public $user_search;
// const SCENARIO_LOGIN = 'login';
const SCENARIO_REGISTER = 'signup';
const SCENARIO_CREATE = 'create';
const SCENARIO_UPDATE = 'update';
const SCENARIO_PASSWORD = 'password';
const SCENARIO_NEWPASSWORD = 'newpassword';
public static function tableName()
{
return 'sim_user';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_email', 'user_fname'], 'required', 'on' => 'update'], // on Update Method scenario
[['user_email', 'user_fname', 'user_password_hash'], 'required', 'on' => 'create'], // on create method scenario
[['user_fname','user_email','user_password_hash','user_password_hash_repeat'], 'required', 'on' => 'signup'], // on signup scenario
[['user_password_hash'],'required' ,'on' => 'newpassword'],// repeat password scenario
['agree','required','requiredValue' => 1,'message' => 'Tick the box', 'on' => 'signup'],// on signup scenario
['user_password_hash','match','pattern'=>'$\S*(?=\S*[a-z])(?=\S*[A-Z])(?=\S*[\d])\S*$','message'=>'Password must have atleast 1 uppercase and 1 number '],
['user_password_hash', 'string', 'min' => 6],
['user_password_hash_repeat', 'compare', 'compareAttribute'=>'user_password_hash', 'skipOnEmpty' => false],
[['user_email'],'email'],
[['user_company', 'user_suspended', 'user_deleted'], 'integer'],
[['user_email'], 'string', 'max' =>255],
['user_email','unique','targetClass'=> '\app\models\SimUser','on'=> 'create'], //create method scenario for unique email
['user_email','unique','targetClass'=> '\app\models\SimUser','on'=> 'signup'],// signup method scenario for unique email
['user_email','unique','targetClass'=> '\app\models\SimUser','on'=> 'update'],//update method scenario for unique email
[['user_fname', 'user_lname'], 'string', 'max' => 45],
[['user_auth_key'], 'string', 'max' => 32],
[['user_access_token'], 'string', 'max' => 100],
['user_email', 'exist', 'on' => self::SCENARIO_PASSWORD]
];
}
Действие контроллера
public function actionSignup()
{
$company = new Company();
$model = new SimUser(['scenario' => SimUser::SCENARIO_REGISTER]);
if ($model->load(Yii::$app->request->post())&& $model->validate() && $company->load(Yii::$app->request->post())&& $company->validate()) {
// var_dump($model); exit()
$model->setPassword($model->user_password_hash);
$model->generateAuthKey();
// $company->save();
$model->company_id = 1;
try{
$model->save();
}catch (Exception $ex) {
var_dump($ex->getMessage()); exit();
}
if ($model->save()){
$auth = Yii::$app->authManager;
$authorRole = $auth->getRole('staff');
$auth->assign($authorRole, $model->user_id);
}
\Yii::$app->user->login($model);
return $this->redirect(['/site/index']);
}
return $this->render('signup', [
'model' => $model,
'company' => $company,
]);
}
Если вы видите правила, я установил для user_password_hash_repeat значение skipOnEmpty = false, что вынуждает пользователя вводить данные в это поле. Если я установлю для него значение true, просто введу пароль и отправлю его, он отправит форму и успешно сохранит модель.
Я также попытался использовать необходимые для user_password_hash_repeat, я не смог сохранить модель.
Что не так в моей настройке правил?
Спасибо!!
1 ответ
Кажется, вам не хватает второго параметра load model
, передайте пустую строку в качестве второго параметра.
Замени это
$model->load(Yii::$app->request->post())
С этим
$model->load(Yii::$app->request->post(), '') //Note: Pass second parameter as empty string
Так что ваши if
состояние будет выглядеть
if ($model->load(Yii::$app->request->post(),'')&& $model->validate() && $company->load(Yii::$app->request->post(),'')&& $company->validate()) {
надеюсь, что это работает.