phpyii2before-save

Yii2 beforeSave


I have a Controller and an updateAction generated with giiant:

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

and I would like to rename a file by overriding beforeSave in Model:

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

    parent::beforeSave($insert);
}

it seems like the model is saved, still the form is rendered after saving, what can not really be. I'm sure that it's because of beforeSave, because if I comment it out, everything works normal. How can the use of beforeSave result in this inconsequent behavior? What am I missing? Thanks a lot!


Solution

  • If you review the source code of beforeSave, you would find that the insertion or updating process will be cancelled if your beforeSave does not return true. "it seems like the model is saved", actually it is not.

    So adjust your code to this:

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