Yii 数据分页及排序

在控制器:

class PostController extends Controller
{
    function actionIndex()
    {
        $criteria = new CDbCriteria();
        $count=Post::model()->count($criteria);
        $pages=new CPagination($count);
 
        // elements per page
        $pages->pageSize=5;
        $pages->applyLimit($criteria);
 
        // sorting
        $sort = new CSort('Post');
        $sort->attributes = array('id', 'title',);
        $sort->applyOrder($criteria);
 
        $models = Post::model()->findAll($criteria);
 
        $this->render('index', array(
            'models' => $models,
            'pages' => $pages,
            'sort' => $sort,
        ));
    }
}

在视图文件中:

<p><?php echo $sort->link('id')?></p>
<p><?php echo $sort->link('title')?></p>
<ol>
<?php foreach($models as $model):?>
    <li>
        <h2><?php echo $model->id?> - <?php echo $model->title?></h2>
    </li>
<?php endforeach?>
</ol>
 
<?php $this->widget('CLinkPager', array(
    'pages' => $pages,
))?>

发表评论

电子邮件地址不会被公开。 必填项已用*标注