Passing parameters between views

Hi, would anyone please tell me how to pass parameters between views?

This is an example of what I am trying to achieve. Two classes are involved:

User (id, username)

Post (id, user_id, content)

The relation is, of course, between User.id and Post.user_id

So I have a view that list some users and I would like to show a link next to every user that says "Create a post as this user". Like this:


List Users


id username link


1 user1 Create a post as this user

2 user2 Create a post as this user

3 user3 Create a post as this user

Therefore, basically what I am trying to do, is to open the “create” view of Post (or call the “create” action of Post, I’m not sure) with the parameter Post.user_id filled.

Usually, the "create" view of Post is:


Create Post


user_id: (textField or dropDownList displaying User.username and having User.id values)

content: (textField)

But after clicking the link, for example, next to "user2" in the user list, I would like to show this:


Create Post


user_id: 2 (label, not a textField)

content: (textField)

And if I click the create button in the form, the post is created with that "user_id" without having the user to specify it.

What would be the best way to accomplish this?

I can see that in the Post controller, I can send parameters to the view, like:




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



Or better yet (I guess):




$model->user_id = 2;

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



But I don’t know how to do this being in the view (where I create the links) and calling this “create” action when the link is clicked. I don’t think that adding parameters to the link URL is a good idea either.

Any help will be appreciated. Thanks in advance!

I think it’s a good idea. Just add user_id to the url. An action can look like:




public function actionCreate($user_id=null)

{

    $model = new Post;

    if ($user_id)

        if ($user = User::model()->findByPk($user_id))

        {

            $model->user_id = $user->id;

            $model->user = $user;

        }

    // ... any code ...

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

        'model'=>$model,

    ));

}



Then in the "create" view you can display a username instead of a dropdown list. Actually you can display a dropdown list too, then the user will be selected automatically.

Thank you andy, this worked for me. :)