use*_*599 4 php before-save yii2
我有一个控制器和一个用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,
]);
}
}
Run Code Online (Sandbox Code Playgroud)
我想通过覆盖模型中的 beforeSave 来重命名文件:
public function beforeSave($insert) {
if ($this->isAttributeChanged('name')) {
rename($this->getOldAttribute('name') . '.pdf', $this->name . '.pdf');
}
parent::beforeSave($insert);
}
Run Code Online (Sandbox Code Playgroud)
似乎模型已保存,但保存后仍呈现表单,实际上不可能。我确信这是因为beforeSave
,因为如果我将其注释掉,一切都会正常。使用 beforeSave 怎么会导致这种不连贯的行为呢?我缺少什么?多谢!
pau*_*aul 10
如果您查看 的源代码beforeSave
,您会发现如果您不返回,则insertion
或updating
过程将被取消。“看起来模型被保存了”,实际上并没有。beforeSave
true
因此,将您的代码调整为:
public function beforeSave($insert) {
if ($this->isAttributeChanged('name')) {
rename($this->getOldAttribute('name') . '.pdf', $this->name . '.pdf');
}
return parent::beforeSave($insert);
}
Run Code Online (Sandbox Code Playgroud)