I am trying to learn Yii, and have looked at Yii documentation, but still do not really get it. I still have no idea how to use the CDataProvider on the Controller and View to display all the blog posts available on the view. Can anyone please advise or give an example based on the following:
The actionIndex in my PostController:
public function actionIndex()
{
$posts = Post::model()->findAll();
$this->render('index', array('posts' => $posts));
));
The View, Index.php:
<div>
<?php foreach ($post as $post): ?>
<h2><?php echo $post['title']; ?></h2>
<?php echo CHtml::decode($post['content']); ?>
<?php endforeach; ?>
</div>
Instead of doing the above, can anyone please advise how to use the CDataProvider to generate instead?
Many thanks.
The best that i can suggest is using a CListView in your view, and a CActiveDataProvider in your controller. So your code becomes somewhat like this :
Controller:
index.php:
_post.php: this file will display each post, and is passed as an attribute of the widget CListView(namely
'itemView'=>'_post'
) in your index.php view.Explanation
Basically in the index action of the controller we are creating a new CActiveDataProvider, that provides data of the Post model for our use, and we pass this dataprovider to the index view.
In the index view we use a Zii widget CListView, which uses the dataProvider we passed as data to generate a list. Each data item will be rendered as coded in the itemView file we pass as an attribute to the widget. This itemView file will have access to an object of the Post model, in the $data variable.
Suggested Reading: Agile Web Application Development with Yii 1.1 and PHP 5
A very good book for Yii beginners, is listed in the Yii homepage.
Edit:
As asked without CListViewindex.php