Home Backend Development PHP Tutorial yii2 implements paging and paging with search functions

yii2 implements paging and paging with search functions

Jun 15, 2018 pm 04:30 PM
yii yii2

This article mainly introduces the implementation of paging in yii2 and an example of the paging function with search. It has certain reference value and interested friends can refer to it.

1. Model configuration

The example will use three models. The article category table and article table can be generated with gii, and the last one is the search verification model. Among them, we only talk about the next joint table and search verification. No other operations are required.

1. Article table association

<?php
//...other code
//关联
public function getCate(){
    return $this->hasOne(ArticleCate::className(),[&#39;id&#39; => &#39;cid&#39;]);
  }
?>
Copy after login

2. Search model

common/models/search/Create ArticleSearch.php

<?php

namespace common\models\search;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Article;

class ArticleSearch extends Article
{
  //public $cname;//文章类别名
  
  /**
   * @inheritdoc
   */
  public function rules()
  {
    return [
      [[&#39;cid&#39;,&#39;created_at&#39;, &#39;updated_at&#39;], &#39;integer&#39;],
      [[&#39;id&#39;, &#39;desc&#39;,&#39;title&#39;,&#39;cover&#39;,&#39;content&#39;], &#39;safe&#39;],
    ];
  }

  /**
   * @inheritdoc
   */
  public function scenarios()
  {
    // bypass scenarios() implementation in the parent class
    return Model::scenarios();
  }

  //搜索
  public function search($params)
  {
    $query = Article::find();
    // $query->joinWith([&#39;cate&#39;]);//关联文章类别表
    // $query->joinWith([&#39;author&#39; => function($query) { $query->from([&#39;author&#39; => &#39;users&#39;]); }]);

    $dataProvider = new ActiveDataProvider([
      &#39;query&#39; => $query,
      &#39;pagination&#39; => [
        &#39;pageSize&#39; => 2,
      ],
    ]);
    // 从参数的数据中加载过滤条件,并验证
    $this->load($params);

    if (!$this->validate()) {
      // uncomment the following line if you do not want to any records when validation fails
      // $query->where(&#39;0=1&#39;);
      return $dataProvider;
    }

    // 增加过滤条件来调整查询对象
    $query->andFilterWhere([
      // &#39;cname&#39; => $this->cate.cname,
      &#39;title&#39; => $this->title,
    ]);

    $query->andFilterWhere([&#39;like&#39;, &#39;title&#39;, $this->title]);
    //$query->andFilterWhere([&#39;like&#39;, &#39;cate.cname&#39;, $this->cname]) ;

    return $dataProvider;
  }
}
Copy after login

2. Use paging

Method 1

First, in the action of the controller, create the paging object and fill it with data:

<?php
//other code
use yii\data\Pagination;
public function actionArticlelist()
  {
    //分页读取类别数据
    $model = Article::find()->with(&#39;cate&#39;);
    $pagination = new Pagination([
      &#39;defaultPageSize&#39; => 3,
      &#39;totalCount&#39; => $model->count(),
    ]);

    $model = $model->orderBy(&#39;id ASC&#39;)
      ->offset($pagination->offset)
      ->limit($pagination->limit)
      ->all();

    return $this->render(&#39;index&#39;, [
      &#39;model&#39; => $model,
      &#39;pagination&#39; => $pagination,
    ]);
  }
?>
Copy after login

Secondly, in the view, the template we output is the current page and Link to the page through the paging object:

<?php
use yii\widgets\LinkPager;
use yii\helpers\Html;
use yii\helpers\Url;
//other code
foreach ($models as $model) {
  // 在这里显示 $model
}

// 显示分页
echo LinkPager::widget([
  &#39;pagination&#39; => $pagination,
  &#39;firstPageLabel&#39;=>"First",
  &#39;prevPageLabel&#39;=>&#39;Prev&#39;,
  &#39;nextPageLabel&#39;=>&#39;Next&#39;,
  &#39;lastPageLabel&#39;=>&#39;Last&#39;,
]);
?>
Copy after login

Method 2

Controller:

<?php
    $query = Article::find()->with(&#39;cate&#39;);

    $provider = new ActiveDataProvider([
      &#39;query&#39; => $query,
      &#39;pagination&#39; => [
        &#39;pageSize&#39; => 3,
      ],
      &#39;sort&#39; => [
        &#39;defaultOrder&#39; => [
          //&#39;created_at&#39; => SORT_DESC,
          //&#39;title&#39; => SORT_ASC,
        ]
      ],
    ]);
    return $this->render(&#39;index&#39;, [
      &#39;model&#39; => $query,
      &#39;dataProvider&#39; => $provider
    ]);
?>
Copy after login

View:

<?php
use yii\grid\GridView;
echo GridView::widget([
  &#39;dataProvider&#39; => $dataProvider,
  //每列都有搜索框 控制器传过来$searchModel = new ArticleSearch(); 
  //&#39;filterModel&#39; => $searchModel,
  &#39;layout&#39;=> &#39;{items}<p class="text-right tooltip-demo">{pager}</p>&#39;,
   &#39;pager&#39;=>[
        //&#39;options&#39;=>[&#39;class&#39;=>&#39;hidden&#39;]//关闭自带分页
        &#39;firstPageLabel&#39;=>"First",
        &#39;prevPageLabel&#39;=>&#39;Prev&#39;,
        &#39;nextPageLabel&#39;=>&#39;Next&#39;,
         &#39;lastPageLabel&#39;=>&#39;Last&#39;,
   ],
  &#39;columns&#39; => [
    //[&#39;class&#39; => &#39;yii\grid\SerialColumn&#39;],//序列号从1开始
    // 数据提供者中所含数据所定义的简单的列
    // 使用的是模型的列的数据
    &#39;id&#39;,
    &#39;username&#39;,
    [&#39;label&#39;=>&#39;文章类别&#39;, /*&#39;attribute&#39; => &#39;cid&#39;,产生一个a标签,点击可排序*/ &#39;value&#39; => &#39;cate.cname&#39; ],
    [&#39;label&#39;=>&#39;发布日期&#39;,&#39;format&#39; => [&#39;date&#39;, &#39;php:Y-m-d&#39;],&#39;value&#39; => &#39;created_at&#39;],
    // 更复杂的列数据
    [&#39;label&#39;=>&#39;封面图&#39;,&#39;format&#39;=>&#39;raw&#39;,&#39;value&#39;=>function($m){
     return Html::img($m->cover,[&#39;class&#39; => &#39;img-circle&#39;,&#39;width&#39; => 30]);
    }],
    [
      &#39;class&#39; => &#39;yii\grid\DataColumn&#39;, //由于是默认类型,可以省略 
      &#39;value&#39; => function ($data) {
        return $data->name; 
        // 如果是数组数据则为 $data[&#39;name&#39;] ,例如,使用 

SqlDataProvider 的情形。
      },
    ],
    [
     &#39;class&#39; => &#39;yii\grid\ActionColumn&#39;,
     &#39;header&#39; => &#39;操作&#39;, 
     &#39;template&#39; => &#39;{delete} {update}&#39;,//只需要展示删除和更新
     /*&#39;headerOptions&#39; => [&#39;width&#39; => &#39;80&#39;],*/
     &#39;buttons&#39; => [
       &#39;delete&#39; => function($url, $model, $key){
           return Html::a(&#39;<i class="glyphicon glyphicon-trash"></i> 删除&#39;,
               [&#39;artdel&#39;, &#39;id&#39; => $key], 
               [&#39;class&#39; => &#39;btn btn-default btn-xs&#39;,
               &#39;data&#39; => [&#39;confirm&#39; => &#39;你确定要删除文章吗?&#39;,]
               ]);
       },
      &#39;update&#39; => function($url, $model, $key){
           return Html::a(&#39;<i class="fa fa-file"></i> 更新&#39;,
              [&#39;artedit&#39;, &#39;id&#39; => $key], 
              [&#39;class&#39; => &#39;btn btn-default btn-xs&#39;]);
       },
      ],
     ],
  ],
]);
?>
Copy after login

3. Search with paging function

  • Create search model (done before)

  • Control incoming data

  • View display control Device code:

<?php
public function actionIndex()
{
 $searchModel = new ArticleSearch();
 $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

  return $this->render(&#39;index&#39;, [
    &#39;searchModel&#39; => $searchModel,
    &#39;dataProvider&#39; => $dataProvider,
  ]);
 }
?>
Copy after login

View:

<?php $form = ActiveForm::begin([
  &#39;action&#39; => [&#39;index&#39;],
   &#39;method&#39; => &#39;get&#39;,
   &#39;id&#39; => &#39;cateadd-form&#39;,
   &#39;options&#39; => [&#39;class&#39; => &#39;form-horizontal&#39;],
]); ?>
          
<?= $form->field($searchModel, &#39;title&#39;,[
   &#39;options&#39;=>[&#39;class&#39;=>&#39;&#39;],
   &#39;inputOptions&#39; => [&#39;placeholder&#39; => &#39;文章搜索&#39;,&#39;class&#39; => &#39;input-sm form-control&#39;],
])->label(false) ?>
  <?= Html::submitButton(&#39;Go!&#39;, [&#39;class&#39; => &#39;btn btn-sm btn-primary&#39;]) ?>
<?php ActiveForm::end(); ?>
<?= GridView::widget([
          &#39;dataProvider&#39; => $dataProvider,
          &#39;layout&#39;=> &#39;{items}<p class="text-right tooltip-demo">{pager}</p>&#39;,
          &#39;pager&#39;=>[
            //&#39;options&#39;=>[&#39;class&#39;=>&#39;hidden&#39;]//关闭自带分页
            &#39;firstPageLabel&#39;=>"First",
            &#39;prevPageLabel&#39;=>&#39;Prev&#39;,
            &#39;nextPageLabel&#39;=>&#39;Next&#39;,
            &#39;lastPageLabel&#39;=>&#39;Last&#39;,
          ],
       //这部分和上面的分页是一样的
Copy after login

Above That’s the entire content of this article. I hope it will be helpful to everyone’s study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About how to write jQuery for search paging in the YII framework

Yii paging using CLinkPager

The above is the detailed content of yii2 implements paging and paging with search functions. For more information, please follow other related articles on the PHP Chinese website!

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks 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)

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.

How to use PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

Symfony vs Yii2: Which framework is better for developing large-scale web applications? Symfony vs Yii2: Which framework is better for developing large-scale web applications? Jun 19, 2023 am 10:57 AM

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

How to use Yii3 framework in php? How to use Yii3 framework in php? May 31, 2023 pm 10:42 PM

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Jun 19, 2023 am 08:09 AM

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

Yii2 Programming Guide: How to run Cron service Yii2 Programming Guide: How to run Cron service Sep 01, 2023 pm 11:21 PM

If you're asking "What is Yii?" check out my previous tutorial: Introduction to the Yii Framework, which reviews the benefits of Yii and outlines what's new in Yii 2.0, released in October 2014. Hmm> In this Programming with Yii2 series, I will guide readers in using the Yii2PHP framework. In today's tutorial, I will share with you how to leverage Yii's console functionality to run cron jobs. In the past, I've used wget - a web-accessible URL - in a cron job to run my background tasks. This raises security concerns and has some performance issues. While I discussed some ways to mitigate the risk in our Security for Startup series, I had hoped to transition to console-driven commands

A few selected CTF exercises will help you learn the yii2 framework! A few selected CTF exercises will help you learn the yii2 framework! Feb 23, 2022 am 10:33 AM

This article will introduce you to the yii2 framework, share a few CTF exercises, and use them to learn the yii2 framework. I hope it will be helpful to everyone.

See all articles