Actioncreate In Usercontroller

Hello everyone!

I’m reading the book and wanna understand the actionCreate of UserController.

Here is the code:


public function actionCreate()

	{

		$model=new User;


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

		{

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

			if($model->save())

				$this->redirect(array('view','id'=>$model->user_id));

		}


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

			'model'=>$model,

		));

	}

I’ve debugged the code (I set the breakpoint at this line)


$model=new User;

and see the fact that:

First the isset($_POST[‘User’]) has value of false and then


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

			'model'=>$model

		));

is executed.

I filled the data to the form and then the control back to the line $model=new User; Now isset($_POST[‘User’]) has value of true, so the code


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

			if($model->save())

				$this->redirect(array('view','id'=>$model->user_id));

executed.

Well this is fairly weird because the line $model=new User; seems to be executed twice.

Is any thing wrong with my debugging or thinking?

Any suggestion would be appreciated!

Cheers!

This is just how PHP works. When you send the first request it is a GET request and there are no post values. The model is only created temporarily to get all the information needed to render the form.

The second request is a post request with the values entered in the form.

This time the model gets actually saved to the database with $model->save();

Are you familiar with how requests work in PHP?

Hi Cebe!

What I know is: to send information from a script (with forms) to another script in PHP we use "get" or "post" method.

The predefined $_GET variable is used to collect values in a form with method=“get”. Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser’s address bar) and has limits on the amount of information to send.

The predefined $_POST variable is used to collect values from a form sent with method="post". Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.

So I’m wondering is it what you’ve mentioned “Are you familiar with how requests work in PHP?”?

If it isn’t what you’re mentioning could you tell me how important of understanding how requests work in PHP and give me a good document, so that I can read and understand it.

Anyway, thank you for your help!

Cheers!