data is saved twice to the database

2019-07-02 00:51发布

问题:

Here is my code:

public function actionPostTest()
{

    if(isset($_POST['Test']))
    {
        $model = new Test();
        $model->attributes = $_POST['Test'];
        if($model->save())
        {
            $this->redirect('postTest');
        }
    }

    $this->render('posttest', array('model'=>new Test()));
}

This is saving the data which coming from a form twice to the database.

What is wrong?

回答1:

Try disabling ajax validation.

Set enableAjaxValidation to false in that view.

Actually there POST happens two times. First Ajax validation and second form submit. You can confirm it by using httpfox in firefox.



回答2:

You can try by this

$model = new Test();
if(isset($_POST['Test']))
{       
    $model->attributes = $_POST['Test'];
    if($model->save())
    {
        unset($_POST['Test']);
        $this->redirect('postTest');
    }
}


标签: php yii