1

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

lin
  • 17,956
  • 4
  • 59
  • 83
santos_mgr
  • 37
  • 1
  • 2
  • 7

1 Answers1

0

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());
itereshchenkov
  • 247
  • 1
  • 3
  • 8
  • Oh, I got it. Actually, I had done some silly mistake by making all the attributes on both the models to safe under rules function. So, on just clicking the action, empty values were being inserted. Thanks anyway. – santos_mgr Aug 19 '14 at 10:10