首页 > 解决方案 > Yii2 beforeSave

问题描述

我有一个控制器和一个用giiant生成的updateAction:

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

    if ($model->load($_POST) && $model->save()) {
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('update', [
            'model' => $model,
        ]);
    }
}

我想通过覆盖模型中的 beforeSave 来重命名文件:

public function beforeSave($insert) {
    if ($this->isAttributeChanged('name')) {
        rename($this->getOldAttribute('name') . '.pdf', $this->name . '.pdf');
    }

    parent::beforeSave($insert);
}

看起来模型被保存了,保存后仍然呈现表单,这不是真的。我确定这是因为beforeSave,因为如果我将其注释掉,一切正常。使用 beforeSave 怎么会导致这种无关紧要的行为?我错过了什么?非常感谢!

标签: phpyii2before-save

解决方案


如果你查看源代码beforeSave,你会发现如果你不返回, insertionorupdating过程将被取消。“看起来模型被保存了”,实际上并没有。beforeSavetrue

因此,将您的代码调整为:

public function beforeSave($insert) {
    if ($this->isAttributeChanged('name')) {
        rename($this->getOldAttribute('name') . '.pdf', $this->name . '.pdf');
    }

    return parent::beforeSave($insert);
}

推荐阅读