Search code examples
phpformsyiimodelmulti-model-forms

data inserting into database on page reload in Yii


data inserting into database on page reload in Yii

I have used two models: CName and CDetails in a single form. All is working well. Except, whenever I reload or refresh that form page, empty data is being inserted into the both tables of the database.

here's the controller code:

 public function actionCreate()
{
    $model=new CName;
    $model1=new CDetails;

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['CName'])
        && ($_POST['CDetails'])
    )
    {
        $model->attributes=$_POST['CName'];
        $model1->attributes=$_POST['CDetails'];

        $valid = $model->validate();
        $valid = $model1->validate() && $valid;

        if($valid)
        {
        if(!empty($model) && !empty($model1)){
         $model->save();
         $model1->save();
         $this->redirect(array('cprimary/create'));}
        }
    }

    $this->render('create',array(
        'model'=>$model,
        'model1'=>$model1,
    ));
}

Now, whenever this page is reloaded, empty values are being inserted on the both model's tables. What is going wrong on the controller? I checked, but, everything seems okay. Please, any comment or instruction would be very helpful.

enter image description here


Solution

  • First of all^ you can get rid of this condition:

    if(!empty($model) && !empty($model1))
    

    it's useless as it's always nonempty.

    Saving data - do you have all fields stated in the rules of the models? At least they should be 'safe'.

    Also you can try to dump the errors:

    var_dump($model->getErrors());