Yii model is validating but data could not be saved

yii
15,970

Solution 1

If save() is returning true and there are no errors as such in your database and queries. Only thing, thats possible is you haven't marked some of the column safe for mass assignment via "$model->attributes".

Make sure the column you are trying to save are marked safe in the "rules" function in your model. You can mark columns safe via adding the following rule in "rules" function in the model.

  array ( "column_name1, column_name2 ....." , "safe" ) 

Solution 2

if you override beforeSave or afterFind method in your model,

public function beforeSave() {
    return true; //don't forget this
}

public function afterFind() {
    return true; //don't forget this
}

make sure you return true for those function

Solution 3

I've just ran into something similar to this. Everything was validating correctly, and $model->save() was returning true, but no data was saved in the database.

The problem and solution was that I was creating the $model object like so:

$model = ClassName::model();

but you need to create the object like so:

$model = new ClassName;

Solution 4

If you have this problem, you replace this:

$model->save(false)

This solves your problem.

If you use $model->save(); the filters is running that is not good for you.

Solution 5

Fire up some logging and see what going on...

Share:
15,970
Shahid Karimi
Author by

Shahid Karimi

Passionate, enthusiast IT professional in true spirit!

Updated on June 26, 2022

Comments

  • Shahid Karimi
    Shahid Karimi almost 2 years

    I have a yii application. Data is validated properly. the $model->validate() returns true but data is not being saved. Is there any way that I know about the error. It does nothing. neither prints error nor any warning.

    if (isset($_POST['Invoice'])) {
        $model->validate();
        $model->attributes = $_POST['Invoice'];
        if (!$model->validate()) {
            die(CVarDumper::dump($model->errors,10,true));
        }
    
        if ($model->save()) {
            die("Data saved");
            $this->redirect(array('view', 'id' => $model->id));
        } else {
            CVarDumper::dump($model->attributes,10,true);
            CVarDumper::dump($model->errors,10,true);
        }
    }