Is There A Method Called After Model::save() Fails?

Is there a method called after a save() fails? Or a way I can detect a failed save() within the model?

Reason:

Image model handles image uploads, extends File

File model handles recording the uploaded file in the DB.

Since I’m storing a hash and the final size of the image, I’m saving the image file first, then recording it in the database. Rather have files with no records than records with no files.

If the save() fails, I’d like a method to delete the stored file. I’ve tried using the __destruct() method in the File model, but something (perhaps a construct of CActiveRecord?) appears to clear out all the attributes before __destruct() can be run. Since the path to the file is based off some attributes of File, this will not work.

Right now, I have overloaded the delete() method, but this has to be called as such:


if($image->save()) {

//do stuff like redirect

} else {

$image->delete()

}

Which goes against some of the logic one would expect in Yii (e.g. No running delete() on new records).

TL;DR I need to do stuff within a model if the save() fails.

you can validate before save




if(!$model->validate())

{

    print_r($model->getErrors());

}

else 

{

    $model->save();

}



you can also check this link

http://www.yiiframework.com/forum/index.php/topic/6405-no-modelvalidation-errors-but-save-return-false/

You always should check the result of save() method call. If you don’t pass the first argument you run the validation before saving and that could fail. Also, sometimes the update/insert query is executed correctly, without an exception, but it doesn’t save data anyway.

As for the logic you mentioned you kind of broke it when you overloaded the delete() method to do something else than removing records from the database. You could just make another method like deleteFile() to be able to call it when there is no corresponding file in the database and also call it from an overloaded delete() method.