Problem submitting form

Hi all,

A beginners questions from someone new to OOP / Yii. I have an update form for user information. When I log in with user #1 and navigate to user/update, all the data of user #1 are displayed in the form. When I then change that data, the form validates but in the database it creates a new user with the data I have entered. Going back to user/update, I can still see the old data of user #1. I suspect the problem is in the controller as the form validates.




	public function actionUpdate()

	{


		// load all attributes and methods from model User / db

		$model=new User;


		if(isset($_POST['User']))

		{ 

			

			$model->attributes=$_POST['User'];

			  

			  if($model->save()){

                                //die("OK");                              

                                $this->redirect('index.php?r=user/welcome');

                       }

	  }


		$this->render('update',array(

			'model'=>$this->loadModel(Yii::app()->user->id),

		));

	}




Any help would be much appreciated. Cheers…

Hi,

It creates a new user data because you declare $model as a new User every time you run update. :)

"$model = new User();" <- creates new user instead of loading old user.

What you should do is:




public function actionUpdate() {

        //load existing user

        $model = User::model()->findByPk(Yii::app()->user->Id);


        if(isset($_POST['User'])) { 

               $model->attributes=$_POST['User'];

               if($model->save()) {

                       //die("OK");                              

                       $this->redirect('index.php?r=user/welcome');

               }

        }


        $this->render('update', array('model' => $model));

}



Also remember: ->attributes only assigns attributes that have rules and/or declared safe.

Hope that helps! Happy coding!

Hi, thanks heaps, your solution has solved my problem. Have a great weekend…