Table of Contents
Yii2分页的使用及其扩展方法详解,yii2分页扩展详解
Home php教程 php手册 Yii2分页的使用及其扩展方法详解,yii2分页扩展详解

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

Jun 13, 2016 am 08:38 AM
yii2 Pagination

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

前言:

说明下我们本篇文章都要讲哪些内容

分页的使用,一步一步的教你怎么做

分页类LinkPager和Pagination都可以自定义哪些属性

分页类LinkPager如何扩展成我们所需要的

第一步,我们来看看yii2自带的分页类该如何去使用?

1、controller action

use yii\data\Pagination;
$query = Article::find()->where(['status' => 1]);
$countQuery = clone $query;
$pages = new Pagination(['totalCount' => $countQuery->count()]);
$models = $query->offset($pages->offset)
  ->limit($pages->limit)
  ->all();
return $this->render('index', [
  'models' => $models,
  'pages' => $pages,
]);
Copy after login

2、View

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

代码基本上可以完全拷贝,修改部分数据即可,相信大多数人都是看得懂的。

我们接下来看第二步,自带的分页类都可以定义哪些属性

首先我们说说LinkPager组件

.pagination参数必填,这个是我们Pagination类的实例

默认分页类是下面这个样子的

.上下页按钮以及10个按钮

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

<&#63;= LinkPager::widget([ 
  'pagination' => $pages, 
  'nextPageLabel' => '下一页', 
  'prevPageLabel' => '上一页', 
]); &#63;>
Copy after login

如果你不想要显示上下页,可以将prevPageLabel和nextPageLabel设置为false

<&#63;= LinkPager::widget([ 
  'pagination' => $pages, 
  'nextPageLabel' => false, 
  'prevPageLabel' => false, 
]); &#63;>
Copy after login

默认不显示首页也尾页,如果你需要,可以这样设置

<&#63;= LinkPager::widget([ 
  'pagination' => $pages, 
  'firstPageLabel' => '首页', 
  'lastPageLabel' => '尾页', 
]); &#63;>
Copy after login

如果你的数据过少,不够2页,默认不显示分页,如果你需要,设置hideOnSinglePage=false即可

<&#63;= LinkPager::widget([ 
  'pagination' => $pages, 
  'hideOnSinglePage' => false, 
]); &#63;>
Copy after login

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

<&#63;= LinkPager::widget([ 
  'pagination' => $pages, 
  'maxButtonCount' => 5, 
]); &#63;>
Copy after login

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

<&#63;= LinkPager::widget([ 
  'pagination' => $pages, 
  'options' => ['class' => 'm-pagination'], 
]); &#63;>
Copy after login

接下来我们谈谈Pagination组件

默认的分页路由是下面这样子的,我们看看能做点什么

/controller/action?page=2&per-page=20

首先,我们是必须要指定总条数totalCount的,没这个参数,分页也是没办法实现的

$pages = new Pagination([ 
  'totalCount' => $totalCount, 
]);
Copy after login

默认分页的数量是20,你可以设置pageSize为你想要的

$pages = new Pagination([ 
  'totalCount' => $totalCount, 
  'pageSize' => 5, 
]);
Copy after login

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

$pages = new Pagination([ 
  'totalCount' => $totalCount, 
  'pageSizeParam' => false, 
]);
Copy after login

我们也可以看到,默认的页面取决于参数page,如果你想改变该参数为p,设置pageParam=p就好

$pages = new Pagination([ 
  'totalCount' => $totalCount, 
  'pageParam' => 'p', 
]);
Copy after login

如果你的分页存在于首页,相信你肯定想要/?p=1而不是/site/index?p=1,我们看看怎么隐藏掉路由

$pages = new Pagination([ 
  'totalCount' => $totalCount, 
  'route' => false, 
]);
Copy after login

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

$pages = new Pagination([ 
  'totalCount' => $totalCount, 
  'validatePage' => false, ]);
Copy after login

最后,我们整点新花样,扩展下他这个自带的分页!别一看见扩展俩字下面的就直接不看了,只有自己学会扩展了,以后才能越来越强!怎么个扩展法呢?我们把分页组件改为上下页那种,具体参考下图做个对比吧

接下来我们就来看看右侧的效果具体是如何通过扩展LinkPager组件实现的。源码分享给大家,喜欢的拿去自己研究即可。

<&#63;php
namespace frontend\components;
use yii\widgets\LinkPager;
use yii\helpers\Html;
class MLinkPager extends LinkPager
{
  public $prevPageLabel = '<i class="fa fa-angle-left"></i>';
  public $nextPageLabel = '<i class="fa fa-angle-right"></i>';
  public $currentCountPageLabel = '第 {currentPage} 页 / 共 {countPage} 页';
  public $currentCountPageClass = 'page-number';
  public $hideOnSinglePage = false;
  public function init () {
    parent::init();
  }
  public function run () {
    $pageCount = $this->pagination->getPageCount();
    if ($pageCount < 2 && $this->hideOnSinglePage) {
      return '';
    }
    $buttons = [];
    $currentPage = $this->pagination->getPage();
    // prev page
    if ($this->prevPageLabel !== false) {
      if (($page = $currentPage - 1) < 0) {
        $page = 0;
      }
      $buttons[] = $this->renderPageButton($this->prevPageLabel, $page, $this->prevPageCssClass, $currentPage <= 0, false);
    }
    // current page / count page
    if ($this->currentCountPageLabel !== false && $pageCount) {
      $currentCountPageLabel = str_replace(['{currentPage}', '{countPage}'], [$currentPage+1, $pageCount], $this->currentCountPageLabel);
      $buttons[] = Html::tag('span', $currentCountPageLabel, array('class' => $this->currentCountPageClass));
    }
    // 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);
    }
    return Html::tag('nav', implode("\n", $buttons), $this->options);
  }
  protected function renderPageButton($label, $page, $class, $disabled, $active)
  {
    $options = ['class' => empty($class) &#63; $this->pageCssClass : $class];
    if ($active) {
      Html::addCssClass($options, $this->activePageCssClass);
    }
    if ($disabled) {
      return false;
    }
    $linkOptions = $this->linkOptions;
    $linkOptions += $options;
    $linkOptions['data-page'] = $page;
    return Html::a($label, $this->pagination->createUrl($page), $linkOptions);
  }
}
Copy after login

如此一来,我们调用MLinkPager实现分页效果像下面这样即可

use frontend\components\MLinkPager; 
<&#63;= MLinkPager::widget([ 
  'pagination' => $pages, 
]); &#63;>
Copy after login

当然,自己扩展的分页组建重在教大家如何去实现分页扩展,难免会有很多问题,如果你有好的意见或者方法,直接给我留言,咱们共同沟通交流。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP development: How to implement table data sorting and paging functions PHP development: How to implement table data sorting and paging functions Sep 20, 2023 am 11:28 AM

PHP development: How to implement table data sorting and paging functions In web development, processing large amounts of data is a common task. For tables that need to display a large amount of data, it is usually necessary to implement data sorting and paging functions to provide a good user experience and optimize system performance. This article will introduce how to use PHP to implement the sorting and paging functions of table data, and give specific code examples. The sorting function implements the sorting function in the table, allowing users to sort in ascending or descending order according to different fields. The following is an implementation form

How to create custom pagination in CakePHP? How to create custom pagination in CakePHP? Jun 04, 2023 am 08:32 AM

CakePHP is a powerful PHP framework that provides developers with many useful tools and features. One of them is pagination, which helps us divide large amounts of data into several pages, making browsing and manipulation easier. By default, CakePHP provides some basic pagination methods, but sometimes you may need to create some custom pagination methods. This article will show you how to create custom pagination in CakePHP. Step 1: Create a custom pagination class First, we need to create a custom pagination class. this

Using JavaScript to implement paging display of table data Using JavaScript to implement paging display of table data Jun 16, 2023 am 10:00 AM

As data continues to grow, tabular display becomes more difficult. Most of the time, the amount of data in a table is so large that it becomes slow to load and users need to constantly browse the page to find the data they want. This article will introduce how to use JavaScript to realize paginated display of table data, making it easier for users to find the data they want. 1. Dynamically create tables. In order to make the paging function more controllable, tables need to be created dynamically. In the HTML page, add a table element similar to the one below.

How to use JavaScript to implement table paging function? How to use JavaScript to implement table paging function? Oct 20, 2023 pm 06:19 PM

How to use JavaScript to implement table paging function? With the development of the Internet, more and more websites use tables to display data. In some cases where the amount of data is large, the data needs to be displayed in pages to improve user experience. This article will introduce how to use JavaScript to implement table paging function and provide specific code examples. 1. HTML structure First, we need to prepare an HTML structure to host tables and paging buttons. We can use &lt;tab

Vue component practice: paging component development Vue component practice: paging component development Nov 24, 2023 am 08:56 AM

Vue component practice: Introduction to paging component development In web applications, the paging function is an essential component. A good paging component should be simple and clear in presentation, rich in functions, and easy to integrate and use. In this article, we will introduce how to use the Vue.js framework to develop a highly customizable paging component. We will explain in detail how to develop using Vue components through code examples. Technology stack Vue.js2.xJavaScript (ES6) HTML5 and CSS3 development environment

Detailed explanation of the principle of MyBatis paging plug-in Detailed explanation of the principle of MyBatis paging plug-in Feb 22, 2024 pm 03:42 PM

MyBatis is an excellent persistence layer framework. It supports database operations based on XML and annotations. It is simple and easy to use. It also provides a rich plug-in mechanism. Among them, the paging plug-in is one of the more frequently used plug-ins. This article will delve into the principles of the MyBatis paging plug-in and illustrate it with specific code examples. 1. Paging plug-in principle MyBatis itself does not provide native paging function, but you can use plug-ins to implement paging queries. The principle of paging plug-in is mainly to intercept MyBatis

How to use Layui to develop a data display page with paging function How to use Layui to develop a data display page with paging function Oct 24, 2023 pm 01:10 PM

How to use Layui to develop a data display page with paging function Layui is a lightweight front-end UI framework that provides simple and beautiful interface components and a rich interactive experience. During development, we often encounter situations where we need to display large amounts of data and perform paging. The following is an example of a data display page with paging function developed using Layui. First, we need to introduce Layui related files and dependencies. Add the following code to the &lt;head&gt; tag of the html page

How to remove jquery in yii2 How to remove jquery in yii2 Feb 17, 2023 am 09:55 AM

How to remove jquery from yii2: 1. Edit the AppAsset.php file and comment out the "yii\web\YiiAsset" value in the variable $depends; 2. Edit the main.php file and add the configuration "'yii" under the field "components" \web\JqueryAsset' => ['js' => [],'sourcePath' => null,]," to remove the jquery script.

See all articles