Having Trouble Understanding Id Assignment

Hi Everyone

First time post on here and new to Yii so looking for a bit of help here in understanding the logic

I’ve started going through this book (2nd Edition) and have come across the following


	/**

	 * Displays a particular model.

	 * @param integer $id the ID of the model to be displayed

	 */

	public function actionView($id)

	{

		$issueDataProvider = new CActiveDataProvider(

			'Issue',

			array(

				'criteria' => array(

					'condition' => 'project_id=:projectId',

					'params' => array(

						'projectId' => $this->loadModel($id)->id

					),

				),

				'pagination' => array(

					'pageSize' => 1

				)

			)

		);

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

			'model'=>$this->loadModel($id),

			'issueDataProvider' => $issueDataProvider

		));

	}

I understand all of the code here and what it does, however it struck me as odd that this line


						'projectId' => $this->loadModel($id)->id

doesn’t just read


						'projectId' => $id

Can anyone explain why this is written this way? Is there any reason it shouldn’t be? I tried the second bit of code to test it and it still works. Any insight into this would be appreciated

Thanks

Jay

Welcome to Yii Family




'projectId' => $this->loadModel($id)->id



The main purpose of this part of code is that First we want to make sure that the $id which is provided must be a valid id of the model.

Let me give example of it

Project Model

id name

1 CSS

2 HTML

3 PHP

now if someone replace the id with 4 in the url to load the 4th record then it will produce the error in case of your code




'projectId' => $id



Whereas in case of above code of the book, it first check that does this id exist in the said table if so then it will load it else generate an error of 404.

Also check the code for loadModel() function inside the controller

Thanks

Hi PeRoChAk

Thanks for the welcome and for answering my question. I figured it was to do with some kind of validation though I overlooked the loadModel method in the Controller. I appreciate you resolving my confusion :)

Thanks

Jay

You are welcome