简体   繁体   English

Yii2更新记录时如何忽略ActiveForm中的输入

[英]Yii2 How to ignore input in ActiveForm when you update a record

i have a problem. 我有个问题。 I have a required field "password". 我有一个必填字段“密码”。 I want to ignore the last field when i clicked on "update" button. 当我单击“更新”按钮时,我想忽略最后一个字段。 Thank you for your attention. 感谢您的关注。

My rules: 我的规则:

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

Also in my User models i used BeforeSave function (to hash my password, when i created a new record). 同样在我的用户模型中,我使用了BeforeSave函数(在创建新记录时对我的密码进行哈希处理)。

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


My controller update action: 我的控制器更新操作:

    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,
        ]);
    }
}

You can use scenarios to do this: docs , but u shouldn't hash password in beforeSave() . 您可以使用以下场景来做到这一点: docs ,但您不应在beforeSave()密码进行哈希处理。 Like in advanced template, create setter for password OR create custom filter in rules + add scenario like 'on' => 'createUser' or 'except' => 'updateUser' . 像在高级模板中一样,为password创建setter或在规则中创建自定义过滤器,然后添加诸如'on' => 'createUser''except' => 'updateUser'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM