Rumah >php教程 >PHP开发 >Yii2分页的使用及其扩展方法详解

Yii2分页的使用及其扩展方法详解

高洛峰
高洛峰asal
2016-12-23 17:02:051679semak imbas

下面我总结了在Yii常用的一些yii分页方式与实例代码,这里有普通分页与ajax实现分页,希望此文章对大家会有所帮助。

第一种:CListView分页  针对对象形式的数据分页

Controller:

public function actionAjax() { 
        $criteria = new CDbCriteria(); 
        //$criteria->order = 'news_id DESC'; 
        $criteria->condition = 'user_id = 1'; 
  
        $dataProvider = new CActiveDataProvider('News', array( 
                    'pagination' => array( 
                        'pageSize' => Yii::app()->params['pagesize'], 
                        'pageVar' => Yii::app()->params['pagevar'], 
                    ), 
                    'criteria' => $criteria, 
                )); 
  
  
        $this->render('view', array( 
            'dataProvider' => $dataProvider, 
        )); 
}

View:

<?php 
$this->widget(&#39;zii.widgets.CListView&#39;, array( 
    &#39;dataProvider&#39; => $dataProvider, //数据 
    &#39;itemView&#39; => &#39;_view&#39;, //显示的模版 
    &#39;id&#39; => Yii::app()->controller->id, 
    &#39;itemsTagName&#39; => &#39;ul&#39;, 
    &#39;ajaxVar&#39; => &#39;&#39;, //默认为page或ajax 去掉后url更简洁 
    &#39;htmlOptions&#39; => array(&#39;class&#39; => Yii::app()->controller->id), 
    &#39;loadingCssClass&#39; => &#39;loading&#39;, //默认为list-view-loading 
    //&#39;template&#39; => &#39;{summary}{sorter}{items}{pager}&#39;,//显示的顺序 
    //&#39;ajaxUpdate&#39; => false, //是否ajax分页  false或分页显示的容器id 
    //&#39;beforeAjaxUpdate&#39; => &#39;before_ajax_update&#39;,   //回调函数 在common.js里完成 
    //&#39;afterAjaxUpdate&#39; => &#39;after_ajax_update&#39;,   
    &#39;emptyText&#39; => &#39; 
<DIV class="alert alert-waning"> 
    暂无数据! 
</DIV> 
&#39;, //无数据时显示内容 
                    &#39;pagerCssClass&#39; => &#39;pagination&#39;, //分页的class 
                    &#39;pager&#39; => array( 
                        &#39;selectedPageCssClass&#39; => &#39;active&#39;, //当前页的class 
                        &#39;hiddenPageCssClass&#39; => &#39;disabled&#39;, //禁用页的class 
                        &#39;header&#39; => &#39;&#39;, //分页前显示的内容 
                        &#39;maxButtonCount&#39; => 10, //显示分页数量 
                        &#39;htmlOptions&#39; => array(&#39;class&#39; => &#39;&#39;), 
                        &#39;firstPageLabel&#39; => &#39;首页&#39;, 
                        &#39;nextPageLabel&#39; => &#39;下一页&#39;, 
                        &#39;prevPageLabel&#39; => &#39;上一页&#39;, 
                        &#39;lastPageLabel&#39; => &#39;末页&#39;, 
                    ), 
                )); 
?>

第二种:CLinkPager  针对数组形式的数据分页

Controller:

public function actionIndex() { 
  
        $criteria = new CDbCriteria(); 
        $criteria->order = &#39;news_id DESC&#39;; 
        $criteria->condition = &#39;user_id = 1&#39;; 
  
        $count = News::model()->count($criteria); 
        $pages = new CPagination($count); 
  
        $pages->pageSize = 10; 
        $pages->applyLimit($criteria); 
        $list = News::model()->findAll($criteria); 
  
        $this->render(&#39;index&#39;, array(&#39;list&#39; => $list, &#39;pages&#39; => $pages)); 
}

View:

<UL> 
    <?php foreach ($list as $item): ?> 
    <LI> 
          
        <DIV class=page-header> 
            <?php echo $item--->news_title; ?> 
        </DIV> 
  
        <DIV class=content> 
            <?php echo $item--->news_intro; ?> 
        </DIV> 
  
    </LI> 
<?php endforeach; ?> 
</UL> 
  
<DIV class=pagination> 
    <?php 
    $this--->widget(&#39;CLinkPager&#39;, array( 
        &#39;pages&#39; => $pages, 
        &#39;selectedPageCssClass&#39; => &#39;active&#39;, //当前页的class 
        &#39;hiddenPageCssClass&#39; => &#39;disabled&#39;, //禁用页的class 
        &#39;header&#39; => &#39;&#39;, //分页前显示的内容 
        &#39;maxButtonCount&#39; => 10, //显示分页数量 
        &#39;htmlOptions&#39; => array(&#39;class&#39; => &#39;&#39;), 
        &#39;firstPageLabel&#39; => &#39;首页&#39;, 
        &#39;nextPageLabel&#39; => &#39;下一页&#39;, 
        &#39;prevPageLabel&#39; => &#39;上一页&#39;, 
        &#39;lastPageLabel&#39; => &#39;末页&#39;, 
            ) 
    ); 
    ?> 
</DIV>

第三种: DAO实现分页.

Controller层:

public function actionReport()
{
$sql = "select remitdate, sum(rate) sumrate from td_delivery 
group by remitdate 
order by remitdate desc";
$criteria=new CDbCriteria();
$result = Yii::app()->db->createCommand($sql)->query();
$pages=new CPagination($result->rowCount);
$pages->pageSize=2; 
$pages->applyLimit($criteria); 
$result=Yii::app()->db->createCommand($sql." LIMIT :offset,:limit"); 
$result->bindValue(&#39;:offset&#39;, $pages->currentPage*$pages->pageSize); 
$result->bindValue(&#39;:limit&#39;, $pages->pageSize); 
$posts=$result->query();
$this->render(&#39;report&#39;,array( 
&#39;posts&#39;=>$posts, 
&#39;pages&#39;=>$pages, 
));
}

View层:

<?php foreach($posts as $row):?> 
 <?php echo CHtml::link($row["remitdate"],array(&#39;delivery/view&#39;,&#39;remitdate&#39;=>$row["sumrate"]));?>
 <?php echo $row["sumrate"]."<br />" ?>
 <?php endforeach;?>
 <?php 
 //分页widget代码: 
 $this->widget(&#39;CLinkPager&#39;,array(&#39;pages&#39;=>$pages));
?>

优点: DAO效率高; 缺点: view层需要自己写一些样式,稍显麻烦一点

第四种:widget实现分页

model层:

/**
* @var string attribute : 日运费 (统计用)
* 需要对新增加的字段做个声明
*/
public $dayrate;
/*
* 统计功能: 统计每日的运费
*/
public function statistics()
{
$criteria = new CDbCriteria;
$criteria->select = &#39;remitdate, sum(rate) AS dayrate&#39;;
$criteria->group = &#39;remitdate&#39;;
return new CActiveDataProvider(get_class($this), array(
&#39;criteria&#39;=>$criteria,
&#39;sort&#39;=>array(
// 表头设置点击排序的字段
&#39;attributes&#39;=>array(
&#39;remitdate&#39;,
&#39;dayrate&#39;=>array(
&#39;asc&#39;=>&#39;dayrate&#39;,
&#39;desc&#39;=>&#39;dayrate DESC&#39;,
)
),
&#39;defaultOrder&#39;=>&#39;remitdate desc&#39;,
),
)); 
}

Controller层:

/**
* 运单统计功能:
* 按日期统计
*/
public function actionReport()
{
$model=new Delivery(&#39;statistics&#39;);
$model->unsetAttributes(); // clear any default values
  
$this->render(&#39;report&#39;,array(
&#39;model&#39;=>$model,
));
}

View层:

<?php $this->widget(&#39;zii.widgets.grid.CGridView&#39;, array(
&#39;id&#39;=>&#39;delivery-grid&#39;,
&#39;dataProvider&#39;=>$model->statistics(),
&#39;filter&#39;=>$model,
&#39;columns&#39;=>array(
&#39;remitdate&#39;,
&#39;dayrate&#39;,
array(
&#39;class&#39;=>&#39;CButtonColumn&#39;,
),
),
));
?>

优点: 可以使用自带的样式; 缺点: 效率略低.


第五种:Ajax分页

YII中ajax分页有多种实现方法,比较传统的就是在view中写JS来实现,大概的就是这样:
在view中js大概逻辑是这样

$(&#39;#listview .yiiPager a&#39;).live(&#39;click&#39;,function(){
        $.ajax({
            url:$(this).attr(&#39;href&#39;),
            success:function(html){
                $(&#39;#listview&#39;).html(html);
            }
        });
        return false;//阻止a标签
});

然后在controller中判断ajax请求,再使用renderPartial方法渲染局部List视图,然后局部视图会被view中的ajax方法填充到局部刷新的div中。controller的大概逻辑是:

if (Yii::app()->request->isAjaxRequest) {
$this->renderPartial(&#39;_comments&#39;,array(
    &#39;model&#39; => $model,
    &#39;comments&#39; => $comments,//在局部视图中foreach得到每条数据
    &#39;pages&#39; => $pages,
   ));
    Yii::app()->end();
}

后来发现YII中的CListview更方便,封装了分页,foreach显示list,还支持数据排序。具体的可以在YII的API手册中发掘。使用CListview是默认ajax分页的,使用方法如下:


controller中:

$criteria = new CDbCriteria();
$criteria->order = &#39;`create_time` DESC&#39;;
$dataProvider = new CActiveDataProvider(&#39;Comments&#39;, array(
    &#39;pagination&#39;=>array(
      &#39;pageSize&#39;=>Yii::app()->params[&#39;commentsPerPage&#39;],//设置分页条数以确定取出数据的条数
  ),
  &#39;criteria&#39;=>$criteria,
  ));
$this->render(&#39;comments&#39;,array(
         &#39;model&#39; => $model,
         &#39;dataProvider&#39; => $dataProvider,
));

然后在view中:

<?php $this->widget(&#39;zii.widgets.CListView&#39;, array(
  &#39;dataProvider&#39;=>$dataProvider,
  &#39;itemView&#39;=>&#39;_comments&#39;,
  //&#39;ajaxUpdate&#39;=> false,//这样就不会AJAX翻页
  &#39;pager&#39; => array(//pager 的配置信息。默认为<CODE>array(&#39;class&#39;=>&#39;CLinkPager&#39;)</CODE>.也可以自己配置
   &#39;nextPageLabel&#39; => &#39;下一页 »&#39;,
   &#39;prevPageLabel&#39; => &#39;« 上一页&#39;
  ),
//在这里还可以配置一些排序规则,具体可以查阅手册
));
?>

这样就实现了Ajax分页,很方便。


希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

更多Yii2分页的使用及其扩展方法详解相关文章请关注PHP中文网!


Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn