Eager Load ActiveDataProvider in Nested CListView

Hi,

I am wondering how I may handle the data in nested CListView. Basically I want to build a page to show all my posts and the comments to these posts. So there are three table in play: tbl_User, tbl_Post and tbl_Comments where

  1. tbl_Post.UID reference tbl_User.UID

  2. tbl_Comments.PostID reference tbl_Post.PostID

I am thinking to use a nested CListView structure to do this and I want to use eager load so that the page doesn’t have to query database to get comments for each post

Some of my code is as below:

//Model/Post.php




class Post extends CActiveRecord

{

	...

    public function relations()

	{

		return array(

			'u' => array(self::BELONGS_TO, 'User', 'UID'),

			'postcomments' => array(self::HAS_MANY, 'Postcomments', 'PostID'),

		);

	}

	...

}

//Controller/PostController.php




class PostController extends Controller

{

	...


	public function actionMyPostWithComments()

	{

		$this->layout = $layout='//layouts/column1';

		

		$dataProvider=new CActiveDataProvider('Post', array(

			'criteria'=>array(

	        	'condition'=>'UID=\''.Yii::app()->user->id.'\'',

	        	'order'=>'CreateDate DESC',

				'with'=>array('postcomments',array(

					'criteria'=>array(

						'order'=>'UpdateDate Desc'

					),

					'pagination'=>array(

						'pageSize'=>2,

					),

				)),

    		),

			'pagination'=>array(

				'pageSize'=>2,

			),

		));

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

			'dataProvider'=>$dataProvider,

			'pageTitle'=>'My Post',

		));

	}	...

}



//view/post/mypostwithcomments.php




<?php

$this->widget('zii.widgets.CListView', array(

	'dataProvider'=>$dataProvider,

	'itemView'=>'_post',

));

?>



//view/post/_post.php




<?php

$this->widget('zii.widgets.CListView', array(

	'dataProvider'=>new CActiveDataProvider($data->postcomments),

	'itemView'=>'_postcomments',

)); 

?>



It seems to give me trouble in /view/post/_post.php when I set the dataProvider. The error is

"Fatal error: Call to a member function getDbCriteria() on a non-object in C:\yii-1.1.9.r3527\framework\web\CActiveDataProvider.php on line 176"

So my question is how I may construct an ActiveDataProvider object when I try to render the nested CListView.

Thanks and any help is appreciated.

Hi

On /view/post/_post.php remove your current code Just add

like

<div>

<?php echo $dataProvider->FirstFieldName; ?>

</div>

<div>

<?php echo $dataProvider->SecondFieldName; ?>

</div>

IF want to same flow than show here your _postcomments.php file (I think no need to this file)

Thanks

Hi, Pravin,

Thanks for your reply, I am not sure if $dataProvider can be accessed in the view file. I think you meant $data. Can you please clarify?

What I want to achieve is within the Post div, show a list of comments associated with the post. therefore I am thinking using nested CListView.

Thanks