How to convert to use the Yii CDataProvider on view?

Deadly 提交于 2019-12-21 12:43:49

问题


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.


回答1:


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:

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: this file will display each post, and is passed as an attribute of the widget CListView(namely 'itemView'=>'_post') in your index.php view.

 <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>

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 CListView

index.php

<?php
 $dataArray = $dataProvider->getData();
foreach ($dataArray as $data){
echo CHtml::encode($data->title);
echo CHtml::encode($data->content);
}
?>


来源:https://stackoverflow.com/questions/9227700/how-to-convert-to-use-the-yii-cdataprovider-on-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!