How do I specify an action's default model

I want to make an action’s model to be the current user’s if not specified. How to do that?

For example, I have an profile action in user controller. If the url is like /user/profile/3 , It will show profile of user whose id is 3 and if the url is like /user/profile it will show the current user’s.


public function actionProfile($id){

			$model=$this->loadModel($id);

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

			'model'=>$model

		));

	}

The simplest way I can think is using the routing rules…


/user/profile/<id:\d+> => 'site/foo'

/user/profile/ => 'site/bar'



or route all to the same action and than do if its numeric do something, else do something else…

I’m not sure if it will work

but you can try also create

actionFoo($id){

if not numeric call actionBar and yii::app()->end();

}

also look here

http://www.yiiframework.com/forum/index.php?/topic/4645-dynamic-default-controller/

Set a default value for the $id=0. Then check in the controller if the $id is empty, if it is, get the ID of the current user and use it instead:


public function actionProfile( $id = 0 ) 

{

	if (empty($id))

	{

		$id = Yii::app()->user->getId();

	}

	

	$model = $this->loadModel( $id );

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

    	'model' => $model

	));

}

Of course, you should handle also the case that the current user is not logged in, but you get the idea…

Brilliant! Good idea! It’s the easiest way by far. Thank you.

Thank you mate! I remember you’ve helped me out several times here.

Your idea may be good, but there’s a better idea by genn. Thanks for your effort anyway.