php - 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 怎么会导致这种无关紧要的行为?我错过了什么?非常感谢!
解决方案
如果你查看源代码beforeSave
,你会发现如果你不返回, insertion
orupdating
过程将被取消。“看起来模型被保存了”,实际上并没有。beforeSave
true
因此,将您的代码调整为:
public function beforeSave($insert) {
if ($this->isAttributeChanged('name')) {
rename($this->getOldAttribute('name') . '.pdf', $this->name . '.pdf');
}
return parent::beforeSave($insert);
}
推荐阅读
- wpf - 在画布上跟踪 WPF 元素
- node.js - 捆绑 Quasar/Express/Electron 应用程序进行生产 - Express-server 无法启动
- css - 移除 Ant Design Tag 的额外上边距
- python - 从 imaplib 获取正确解码的邮箱名称
- docker - 如何在 databricksConnectDocker 上运行 Docker 映像而不会出现错误“tiny”
- python - 如何测量时间复杂度
- composer-php - 为什么作曲家中的存储库本地指令不起作用?
- python - 输入提示返回,返回None,根本不返回?
- php - 使用 laravel 为 foreach() 提供的参数无效
- javascript - 如何使用 Webpack 加载器读取 React js App 中的本地 html 文件内容?