這篇文章主要介紹了Yii列表定義與使用分頁方法,總結(jié)分析了3種方法供大家參考,涉及Yii針對數(shù)據(jù)庫的查詢、分頁計算及相關(guān)類與方法的使用技巧,需要的朋友可以參考下
方法一:控制器定義
function actionIndex(){
$criteria = new CDbCriteria();
$count=Article::model()->count($criteria);
$pages=new CPagination($count);
// 返回前一頁
$pages->pageSize=10;
$pages->applyLimit($criteria);
$models = Post::model()->findAll($criteria);
$this->render('index', array(
'models' => $models,
'pages' => $pages
));
}
視圖定義:
<?php foreach($models as $model): ?>
// 顯示一個模型
<?php endforeach; ?>
// 顯示分頁
<?php $this->widget('CLinkPager', array(
'pages' => $pages,
)) ?>
方法二:控制器定義:
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('News',array(
'criteria'=>array(
'condition'=>'status=1',
'order'=>'create_time DESC',
'with'=>array('author'),
),
'pagination'=>array(
'pageSize'=>20,
),
));
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
視圖文件:
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>
方法三:視圖文件
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'news-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'template'=>'{items}{summary}{pager}',
<span style="white-space:pre"> </span> 'pager'=>array(
'class'=>'CLinkPager',
'header'=>'分頁:',
'prevPageLabel'=>'上一頁',
'nextPageLabel'=>'下一頁',
),
<span style="white-space:pre"> </span> 'summaryText'=>'頁數(shù):{pages}/{page}頁',
<span style="white-space:pre"> </span>'columns'=>array(
'id',
array('name'=>'title',
'htmlOptions'=>array('width'=>'20%'),
'value'=>'mb_substr($data->title,0,10,"utf-8")',
),
array('name'=>'content',
'htmlOptions'=>array('width'=>'20%'),
'value'=>'mb_substr(strip_tags($data->content),0,10,"utf-8")',
),
array('name'=>'type',
'value'=>'News::model()->getNewsType($data->type)',
),
'user',
array('name'=>'status',
'value'=>'News::model()->getNewsStatus($data->status)',
),
array(
'class'=>'CButtonColumn',
),
),
));
數(shù)據(jù)模型類:
public function search()
{
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('title',$this->title,true);
$criteria->compare('content',$this->content,true);
$criteria->compare('type',$this->type);
$criteria->compare('user',$this->user,true);
$criteria->compare('status',$this->status);
$criteria->compare('create_data',$this->create_data,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>50,
),
));
}
希望本文所述對大家基于Yii框架的PHP程序設(shè)計有所幫助。