How to convert to YIA CDataProvider for viewing?

I'm trying to find out Yii and looked at the Yii documentation, but still don't understand. I still don't know how to use CDataProvider on the controller and in the view to display all the blog posts available in the view. Someone can advise or give an example based on the following:

ActionIndex in my PostController:

public function actionIndex() { $posts = Post::model()->findAll(); $this->render('index', array('posts' => $posts)); )); 

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 advise how to use CDataProvider to generate instead?

Many thanks.

+6
source share
1 answer

The best I can offer is to use CListView in your view, and CActiveDataProvider in your controller. So your code looks something 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 every post and is passed as an attribute of the CListView widget (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 indexing action of the controller, we create a new CActiveDataProvider that provides the data of the Post model for our use, and we pass this dataproder to the index view.
In the index window, we use the Zii CListView widget, which uses the dataProvider, which we passed as data to create the list. Each data item will be displayed as encoded in the itemView file, which we pass as a widget attribute. This itemView file will have access to the Post model object in the $ data variable.

Suggested Reading: Agile Web Application Development with Yii 1.1 and PHP 5
A very good Yii beginner book, listed on the Yii homepage.

Edit:

As requested without CListView

index.php

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

Source: https://habr.com/ru/post/908141/


All Articles