2016-12-06 9 views
0

問題があります。私は必須フィールド "パスワード"を持っています。 "更新"ボタンをクリックしたときに最後のフィールドを無視したい。ご清聴ありがとうございました。Yii2レコードを更新するときにActiveFormの入力を無視する方法

マイルール:私は(私は新しいレコードを作成したとき、私のパスワードをハッシュする)BeforeSave機能を使用し、私のユーザモデルでも

public function rules() 
    { 
     return [ 
      [['username', 'role_id', 'surname', 'name', 'patronymic', 'email', 'password', 'department_id'], 'required'], 
      [['role_id', 'department_id'], 'integer'], 
      [['date_of_birth'], 'safe'], 
      [['password'], 'string', 'min' => 8], 
      [['username', 'surname', 'name', 'patronymic', 'email', 'telephone', 'skype', 'avatar', 'password'], 'string', 'max' => 255], 
      [['role_id'], 'exist', 'skipOnError' => true, 'targetClass' => Roles::className(), 'targetAttribute' => ['role_id' => 'id']], 
      [['department_id'], 'exist', 'skipOnError' => true, 'targetClass' => Department::className(), 'targetAttribute' => ['department_id' => 'id']], 
      [['file'], 'file', 'extensions' => 'png, jpg'], 
      ['email', 'email'], 
      [['email', 'username'], 'unique'], 
];` 

public function beforeSave($insert) 
{ 
    if (isset($this->password)) { 
     $this->password = Yii::$app->getSecurity()->generatePasswordHash($this->password); 
    } 
    return parent::beforeSave($insert); 
} 


私のコントローラの更新アクション:あなたがこれを行うにシナリオを使用することができます

public function actionUpdate($id) 
{ 
    $model = $this->findModel($id); 

    if ($model->load(Yii::$app->request->post()) && $model->save()) { 

     $imageName = uniqid(); 
     $model->file = UploadedFile::getInstance($model, 'file'); 
     if (!empty($model->file)){ 
      $model->file->saveAs('uploads/'.$imageName.'.'.$model->file->extension); 
      $model->avatar = 'uploads/'.$imageName.'.'.$model->file->extension; 
      $model->save(false); 
     } 
     return $this->redirect(['view', 'id' => $model->id]); 
    } else { 
     return $this->render('update', [ 
      'model' => $model, 
     ]); 
    } 
} 

答えて

0

docs、しかし、uはbeforeSave()でパスワードをハッシュべきではありません。高度なテンプレートと同様に、passwordのセッターを作成するか、ルールでカスタムフィルターを作成し、'on' => 'createUser'または'except' => 'updateUser'のようなシナリオを追加します。

関連する問題