giovaZ
giovaZ

Reputation: 1470

Yii2 model with scenarios save all except the password field

In my application i've a model called User Where i've implemented a scenario for validations.

const SCENARIO_RESET_PASSWORD = 'passwordReset';

public function rules()
{
    return[
        [['name','surname','password','username','id_role'], 'required'],
        [['email','email2'], 'email'],
        [['username','email'], 'unique'],
        ['confirmPassword', 'compare', 'compareAttribute'=>'password', 'on' => self::SCENARIO_RESET_PASSWORD]
    ];
}

With this configuration i can create a new User, delete one and update all fields except for 'password'.

This is the action in my controller:

public function actionUpdate($id)
{
    $user = User::findOne($id);

    if($user->load(Yii::$app->request->post())&& $user->validate()) {
      $user->update();
      $this->redirect(\yii\helpers\Url::toRoute('index'));
    }

    return $this->render('update',[
        'user' => $user,
    ]);

}

i've already checked that the field 'password' is passed on post parameters with success.

and this is my view:

    <h1> Edit User </h1>
<?php
     $form = ActiveForm::begin([
            'id' => 'active-form',
            'options' =>  [
                'class' => 'form-horizontal',
                'enctype' => 'multipart/form-data'
            ],
        ]); 
?>

<?= $form->errorSummary($user); ?>

<?= $form->field($user, 'name') ?>

<?= $form->field($user, 'surname') ?>

<?= $form->field($user, 'username') ?>

<?= $form->field($user, 'email') ?>

<?= $form->field($user, 'password')->passwordInput() ?>

<?php  if(Yii::$app->user->identity->id_role === User::USER_ADMIN): ?>

<?= $form->field($user, 'id_role')->dropDownList(
        Role::find()->select(['name','id'])->indexBy('id')->column(),
        ['prompt'=>'Select a role']
        );
?>

<?php endif; ?>

<div class="form-group">
    <?= Html::submitButton('Save the user', ['class' => 'btn btn-success']) ?>
</div>

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

I really don't know why i'm getting this error

Upvotes: 0

Views: 1565

Answers (1)

Manoj S Kadlag
Manoj S Kadlag

Reputation: 250

Please remove

'on' => self::SCENARIO_RESET_PASSWORD

or define your SCENARIO in your controller action as

 $user->scenario = 'SCENARIO_RESET_PASSWORD';

Upvotes: 1

Related Questions