yii框架-yii2分页的使用与扩展(十五)

今天主要是总结一下如何使用yii2中分页功能,从下面三个方面来讲。
(1)分页的使用
(2)分页类LinkPager和Pagination都可以自定义哪些属性
(3)分页类LinkPager如何扩展成我们所需要的

一、分页的使用
(1)Pagination类可以分辨单独使用。也即是和model分离。
例如在controller 的action中:
use yii\data\Pagination;
$query = Article::find()->where(['status' => 1]);
$countQuery = clone $query;
//分页实例对象,必须要设置totalCount
$pages = new Pagination(['totalCount' => $countQuery->count()]);
//数据模型
$models = $query->offset($pages->offset)
  ->limit($pages->limit)
  ->all();
//分别返回对象
return $this->render('index', [
  'models' => $models,
  'pages' => $pages,
]);

那么在view中:
use yii\widgets\LinkPager;
//循环展示数据
foreach ($models as $model) {
  // ......
}
//显示分页页码
echo LinkPager::widget([
  'pagination' => $pages,

])


(2)如果是结合yii\data\ActiveDataProvider这个使用,主要是配置pagination:
$provider = new ActiveDataProvider([
    'query' => $query,
    'pagination' => [
        'pageSize' => 5,
    ],
]);
那么在view就可以直接用yii\grid\GridView,配置pager属性
<?= GridView::widget([
'id' => 'grid',
'dataProvider' => $dataProvider,
'layout' => '{items}{pager}',
'showFooter' => false,
'caption' => '注册用户',
'captionOptions' => [
'data' => ['id' => 1, 'name' => 'yii'],
'style' => ['text-align' => 'center']
],
'pager' =>[
        'class' => GoPager::className(),
'firstPageLabel' => '首页',
        'prevPageLabel' => '《',
        'nextPageLabel' => '》',
        'lastPageLabel' => '尾页',
        'goPageLabel' => true,
        'totalPageLable' => '共x页',
        'goButtonLable' => 'GO',
        'maxButtonCount' => 5

]


二、自定义属性设置样式。
首先我们说说LinkPager组件
pagination参数必填,这个是我们Pagination类的实例,返回的$pages.
默认的分页样式

默认页数按钮显示10个。


首先,我们把上下页的按钮修改成中文

<?= LinkPager::widget([ 

  'pagination' => $pages, 
  'nextPageLabel' => '下一页', 
  'prevPageLabel' => '上一页', 
]); ?>
如果你不想要显示上下页,可以将prevPageLabel和nextPageLabel设置为false

<?= LinkPager::widget([ 
  'pagination' => $pages, 
  'nextPageLabel' => false, 
  'prevPageLabel' => false, 
]); 

?>


默认不显示首页也尾页,如果你需要,可以这样设置
<?= LinkPager::widget([ 
  'pagination' => $pages, 
  'firstPageLabel' => '首页', 
  'lastPageLabel' => '尾页', 
]); 

?>


如果你的数据过少,不够2页,默认不显示分页,如果你需要,设置hideOnSinglePage=false即可
<?= LinkPager::widget([ 
  'pagination' => $pages, 
  'hideOnSinglePage' => false, 
]); 
?>

默认显示的页码为10页,可以设置maxButtonCount为你想要展示的页数

<?= LinkPager::widget([ 

  'pagination' => $pages, 
  'maxButtonCount' => 5, 
]); 
?>

有些人不喜欢默认的样式,想要分页带上自己的样式,可以设置options,不要忘了自行实现pre,next,disabled等样式

<?= LinkPager::widget([ 

  'pagination' => $pages, 
  'options' => ['class' => 'm-pagination'], 
]); 
?>

接下来我们谈谈Pagination组件
默认的分页路由是下面这样子的,我们看看能做点什么
/controller/action?page=2&per-page=20

首先,我们是必须要指定总条数totalCount的,没这个参数,分页也是没办法实现的
$pages = new Pagination([ 
  'totalCount' => $totalCount, 

]);


默认分页的数量是20,你可以设置pageSize为你想要的
$pages = new Pagination([ 
  'totalCount' => $totalCount, 
  'pageSize' => 5, 
]);

从上面的分页路由我们可以看到,默认带的有每页的数量per-page 如果你不想显示该参数,设置pageSizeParam=false就好
$pages = new Pagination([ 
  'totalCount' => $totalCount, 
  'pageSizeParam' => false, 

]);


我们也可以看到,默认的页面取决于参数page,如果你想改变该参数为p,设置pageParam=p就好
$pages = new Pagination([ 
  'totalCount' => $totalCount, 
  'pageParam' => 'p', 

]);


如果你的分页存在于首页,相信你肯定想要/?p=1而不是/site/index?p=1,我们看看怎么隐藏掉路由
$pages = new Pagination([ 
  'totalCount' => $totalCount, 
  'route' => false, 
]);

可能你会发现分页类Pagination有一个bug,假如我们只有1页的数据,但是手动更改地址栏的page=20的时候,也会显示page=1的数据?当然,这在大部分接口API中就很让人厌烦。但是,这并非bug,而是一种友好的验证。设置validatePage=false即可避免掉该问题
$pages = new Pagination([ 
  'totalCount' => $totalCount, 
  'validatePage' => false, 
]);

接下来我们研究一下如何扩展自己分分页样式,变成如下样式


主要是重写run()和renderPageButtons()两个方法
代码如下:
namespace app\component;
use yii\widgets\LinkPager;
use yii\helpers\Html;

class GoPager extends LinkPager {
	/**
	*@var boole|string. weather show totalPage
	*You can do not set the property by using defult,so the totalPage button not show in the html. 
	*if you set it as string,eg: totalPageLable => '共x页'.note that the 'x' will be replaced by $pageCount.so the 'x' must be seted.
	*/
	public $totalPageLable = false;

	/**
	*@var boole if is seted true,the goPageLabel can be show in the html.
	*
	*/
	public $goPageLabel = false;

	/**
	*@var array.options about the goPageLabel(input) 
	*goPageLabelOptions => [
	*		'class' =>
	*		'data-num' => 
	*		'style' =>
	*	]
	*
	*/
	public $goPageLabelOptions = [];

	/**
	*@var boole | string. weather show in go page button
	*
	*/
	public $goButtonLable = false;

	/**
	*@var array.options about the goButton
	*
	*/
	public $goButtonLableOptions = [];
	
	/**
	*
	**/
	public function init() {
		parent::init();

	}

	public function run()
    {
        if ($this->registerLinkTags) {
            $this->registerLinkTags();
        }
        echo $this->renderPageButtons();
    }

	protected function renderPageButtons() {

		$pageCount = $this->pagination->getPageCount();
        if ($pageCount < 2 && $this->hideOnSinglePage) {
            return '';
        }

        $buttons = [];
        $currentPage = $this->pagination->getPage();
        // first page
        $firstPageLabel = $this->firstPageLabel === true ? '1' : $this->firstPageLabel;
        if ($firstPageLabel !== false) {
            $buttons[] = $this->renderPageButton($firstPageLabel, 0, $this->firstPageCssClass, $currentPage <= 0, false);
        }

        // prev page
        if ($this->prevPageLabel !== false) {
            if (($page = $currentPage - 1) < 0) {
                $page = 0;
            }
            $buttons[] = $this->renderPageButton($this->prevPageLabel, $page, $this->prevPageCssClass, $currentPage <= 0, false);
        }

        // internal pages
        list($beginPage, $endPage) = $this->getPageRange();
        for ($i = $beginPage; $i <= $endPage; ++$i) {
            $buttons[] = $this->renderPageButton($i + 1, $i, null, false, $i == $currentPage);
        }

        // next page
        if ($this->nextPageLabel !== false) {
            if (($page = $currentPage + 1) >= $pageCount - 1) {
                $page = $pageCount - 1;
            }
            $buttons[] = $this->renderPageButton($this->nextPageLabel, $page, $this->nextPageCssClass, $currentPage >= $pageCount - 1, false);
        }

        // last page
        $lastPageLabel = $this->lastPageLabel === true ? $pageCount : $this->lastPageLabel;
        if ($lastPageLabel !== false) {
            $buttons[] = $this->renderPageButton($lastPageLabel, $pageCount - 1, $this->lastPageCssClass, $currentPage >= $pageCount - 1, false);
        }

        // total page
       	if ($this->totalPageLable) {
        	$buttons[] = Html::tag('li',Html::a(str_replace('x',$pageCount,$this->totalPageLable),'javascript:return false;',[]),[]); 	
        }

        //gopage
        if ($this->goPageLabel) {
        	$input = Html::input('number',$this->pagination->pageParam,$currentPage+1,array_merge([
        			'min' => 1,
        			'max' => $pageCount,
        			'style' => 'height:34px;width:80px;display:inline-block;margin:0 3px 0 3px',
        			'class' => 'form-control',
        		],$this->goPageLabelOptions));

        	$buttons[] = Html::tag('li',$input,[]);
        }

        // gobuttonlink
        if ($this->goPageLabel) {
        	$buttons[] = Html::submitInput($this->goButtonLable ? $this->goButtonLable : '跳转',array_merge([
        			'style' => 'height:34px;display:inline-block;',
        			'class' => 'btn btn-primary'
        		],$this->goButtonLableOptions));
        }
        $ul = Html::tag('ul', implode("\n", $buttons), $this->options);
        return Html::tag('form',$ul,[]);
	}
}

单独使用具体用法:
GoPager::widget([
'firstPageLabel' => '首页',
    'prevPageLabel' => '《',
    'nextPageLabel' => '》',
    'lastPageLabel' => '尾页',
    'goPageLabel' => true,
    'totalPageLable' => '共x页',
    'goButtonLable' => 'GO',
    'maxButtonCount' => 5
    .....
]);

如果是结合yii\grid\GridView使用,配置pager的属性:
<?= GridView::widget([
  ....
'pager' =>[
        'class' => GoPager::className(),
'firstPageLabel' => '首页',
        'prevPageLabel' => '《',
        'nextPageLabel' => '》',
        'lastPageLabel' => '尾页',
        'goPageLabel' => true,
        'totalPageLable' => '共x页',
        'goButtonLable' => 'GO',
        'maxButtonCount' => 5
],

]);

友情推荐

本人已开源基于swoole扩展实现的轻量级框架

https://github.com/bingcool/swoolefy


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值