我正在尝试学习Yii,并查看了Yii文档,但仍然没有真正了解它。我仍然不知道如何使用Controller和View上的CDataProvider来显示视图上可用的所有博客文章。有人能根据以下内容提出建议或举个例子吗:
我的PostController中的actionIndex:
public function actionIndex()
{
$posts = Post::model()->findAll();
$this->render('index', array('posts' => $posts));
));
视图,索引.php:
<div>
<?php foreach ($post as $post): ?>
<h2><?php echo $post['title']; ?></h2>
<?php echo CHtml::decode($post['content']); ?>
<?php endforeach; ?>
</div>
请有人建议如何使用CDataProvider来生成,而不是执行上述操作吗?
非常感谢。
我能建议的最好的方法是在视图中使用CListView,在控制器中使用CActiveDataProvider。因此,您的代码变得有点像这样:
控制器:
public function actionIndex()
{
$dataProvider = new CActiveDataProvider('Post');
$this->render('index', array('dataProvider' => $dataProvider));
}
index.php:
<?php
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_post', // refers to the partial view named '_post'
// 'enablePagination'=>true
)
);
?>
_post.php:该文件将显示每个帖子,并作为index.php视图中的小部件CListView(即'itemView'=>'_post'
)的属性传递。
<div class="post_title">
<?php
// echo CHtml::encode($data->getAttributeLabel('title'));
echo CHtml::encode($data->title);
?>
</div>
<br/><hr/>
<div class="post_content">
<?php
// echo CHtml::encode($data->getAttributeLabel('content'));
echo CHtml::encode($data->content);
?>
</div>
解释
基本上,在控制器的索引操作中,我们正在创建一个新的CActiveDataProvider,提供Post模型的数据供我们使用,并将此数据提供程序传递给索引视图
在索引视图中,我们使用Zii小部件CListView,它使用我们作为数据传递的dataProvider来生成列表。每个数据项都将在itemView文件中呈现为编码,我们将其作为属性传递给小部件。此itemView文件将可以访问$data变量中Post模型的对象。
建议阅读:Yii1.1和PHP5的敏捷Web应用程序开发
Yii主页上列出了一本非常适合Yii初学者的书。
编辑:
在没有CListView 的情况下按要求index.php
<?php
$dataArray = $dataProvider->getData();
foreach ($dataArray as $data){
echo CHtml::encode($data->title);
echo CHtml::encode($data->content);
}
?>