2016-12-06 100 views
0

我遇到問題。我有一個必填字段「密碼」。當我點擊「更新」按鈕時,我想忽略最後一個字段。感謝您的關注。Yii2如何在更新記錄時忽略ActiveForm中的輸入

我的規則:

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'], 
];` 

而且在我的用戶模型,我用BeforeSave功能(散列我的密碼,當我創建了一個新的紀錄)。

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,但你不應該在beforeSave()散列密碼。就像在高級模板中一樣,爲password創建設置器,或者在規則+添加場景中創建自定義過濾器,如'on' => 'createUser''except' => 'updateUser'

相關問題