How to convert to use the Yii CDataProvider on vie

2019-04-07 14:24发布

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.

标签: php yii
1条回答
Luminary・发光体
2楼-- · 2019-04-07 14:25

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);
}
?>
查看更多
登录 后发表回答