Home Backend Development C#.Net Tutorial Yii2 implements paging, example of paging function with search

Yii2 implements paging, example of paging function with search

Jan 13, 2017 pm 03:53 PM

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

1

2

3

4

5

6

7

<?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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

<?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. Paging use

Method 1

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<?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 is linked to the page through the paging object:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<?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 Two

Controller:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<?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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

<?php

use yii\grid\GridView;

echo GridView::widget([

  &#39;dataProvider&#39; => $dataProvider,

  //每列都有搜索框 控制器传过来$searchModel = new ArticleSearch();

  //&#39;filterModel&#39; => $searchModel,

  &#39;layout&#39;=> &#39;{items}<div class="text-right tooltip-demo">{pager}</div>&#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 (already done before)

Control incoming data

View display controller code:

1

2

3

4

5

6

7

8

9

10

11

12

<?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:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?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}<div class="text-right tooltip-demo">{pager}</div>&#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

The above is the entire content of this article. I hope it will be helpful to everyone’s learning. I also hope that everyone will support PHP Chinese. net.

For more yii2 implementation of paging, paging function examples with search and related articles, please pay attention to 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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

What is the role of char in C strings What is the role of char in C strings Apr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

How to use various symbols in C language How to use various symbols in C language Apr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

How to handle special characters in C language How to handle special characters in C language Apr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

The difference between char and wchar_t in C language The difference between char and wchar_t in C language Apr 03, 2025 pm 03:09 PM

In C language, the main difference between char and wchar_t is character encoding: char uses ASCII or extends ASCII, wchar_t uses Unicode; char takes up 1-2 bytes, wchar_t takes up 2-4 bytes; char is suitable for English text, wchar_t is suitable for multilingual text; char is widely supported, wchar_t depends on whether the compiler and operating system support Unicode; char is limited in character range, wchar_t has a larger character range, and special functions are used for arithmetic operations.

How to convert char in C language How to convert char in C language Apr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

How to use char array in C language How to use char array in C language Apr 03, 2025 pm 03:24 PM

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

See all articles