Informer February 2016

Using more than one model in ListView

I read this post and answer give by Songwut K. in this question:

Yii2 ListView and dataprovider

But i want to know that is possible to use second model in _item. Suppose the _item is a post in the forum that retrieves data from the $model but I'd like to use a different model like $comment for me comment on a this post and view the post together with a commentary as one _item. Imagie that item is post on facebook and it display only text, date and user which write this post. But how i can add comment to this from other model? I just want to pass my $comment to _item view.

I was tried add new Commnet in my controller:

public function actionIndex()
    {
        $model = new NewsForm();
        $searchModel = new NewsSearch();
        $comment= new UrComment();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->setSort(['defaultOrder' => ['Id'=>SORT_DESC]]);

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $model->saveNews();
            return $this->redirect(['/content/news']);
        } else {
            return $this->render('index', [
                        'model' => $model,
                        'searchModel' => $searchModel,
                        'dataProvider' => $dataProvider,
                        'comment' => $comment
            ]);
        }
    }

And render this to index. But i can use my $comment only in index how can i pass this to _item? i tried this:

 <?php
                echo ListView::widget( [
                    'dataProvider' => $dataProvider,
                    'itemView' => '_item',
                    'summary'=>'', 
                    'comment' => $comment
         

Answers


soju February 2016

You should simply use viewParams :

Additional parameters to be passed to $itemView when it is being rendered. This property is used only when $itemView is a string representing a view name.

e.g. :

<?= ListView::widget( [
    'dataProvider' => $dataProvider,
    'itemView' => '_item',
    'viewParams' => ['comment' => $comment],
    'summary'=>'', 
]); ?>

Post Status

Asked in February 2016
Viewed 2,703 times
Voted 7
Answered 1 times

Search




Leave an answer