YII2 implementation pagination with search pagination feature example

Source: Internet
Author: User
Tags yii
This article introduces the content is about YII2 implementation paging, with a search of paging function example, has a certain reference value, now share to everyone, the need for friends can refer to

The case will use three models. The article category table and the article table are generated with the GII, and the last one is the search validation model. Where only the next linked table and search validation are spoken. Others do not operate.

1. Article Table Association

<?php//...other code//Associated Public Function getcate () {    return $this->hasone (Articlecate::classname (), [' id ' = > ' cid ');  }? >

2. Search Models

common/models/search/Creating 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;//article Category name/** * @inheritdoc */Public Function rules () {    return [[' Cid ', ' created_at ', ' updated_at '], ' integer ', [[' ID ', ' desc ', ' title ', ' cover ', ' content '], ' safe '],  ];    }/** * @inheritdoc */Public Function scenarios () {//Bypass scenarios () implementation in the parent class  return Model::scenarios ();    }//Search for Public Function search ($params) {$query = Article::find (); $query->joinwith ([' Cate ']);//related Article Category table//$query->joinwith ([' Author ' = function ($query) {$query->from ( [' Author ' = ' users '];     }]);      $dataProvider = new Activedataprovider ([' query ' = = $query, ' pagination ' = = [' pageSize ' + = 2,    ],    ]);     Load the filter condition from the data of the parameter and verify the $this->load ($params); if (! $this->validate ()) {//UncommentThe following line if you don't want to any records when validation fails//$query->where (' 0=1 ');    return $dataProvider; }//Add filter condition to adjust Query object $query->andfilterwhere ([//' cname ' = = $this->cate.cname, ' title ' + $this     ->title,]);    $query->andfilterwhere ([' Like ', ' title ', $this->title]);     $query->andfilterwhere ([' Like ', ' cate.cname ', $this->cname]);  return $dataProvider; }}

Second, the use of paging

Way One

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

<?php//other codeuse yii\data\pagination;public function actionarticlelist ()  {    //paging read class data    $model = Article::find ()->with (' Cate ');    $pagination = new Pagination ([      ' defaultpagesize ' = 3,      ' totalcount ' = ' + ' $model->count (),    ]);     $model = $model->orderby (' id ASC ')      ->offset ($pagination->offset)      ->limit ($pagination Limit)      ->all ();     return $this->render (' index ', [      ' model ' = $model,      ' pagination ' + $pagination,    ]);  >


Second, in the view we output a template that is the current page and is linked to the page by a paging object:

<?phpuse yii\widgets\linkpager;use yii\helpers\html;use yii\helpers\url;//other Codeforeach ($models as $model) {  //Show here $model}//Show paging echo linkpager::widget ([  ' pagination ' = = $pagination,  ' firstpagelabel ' = ') First ",  ' prevpagelabel ' = ' Prev ',  ' nextpagelabel ' = ' Next ',  ' lastpagelabel ' = ' last ',]);? >


Way Two

Controller:

<?php    $query = Article::find ()->with (' Cate ');     $provider = new Activedataprovider ([      ' query ' = = $query,      ' pagination ' = = [        ' pageSize ' + = 3,      ],      ' sort ' = = [        ' defaultorder ' + = [          //' created_at ' + sort_desc,          //' title ' = = SORT_ASC,        ]      ],    ]);    return $this->render (' index ', [      ' model ' = ' $query,      ' dataprovider ' + $provider    ]); >


View:

<?phpuse Yii\grid\gridview;echo gridview::widget ([' dataprovider ' = $dataProvider,//Each column has a search box controller passed over $   Searchmodel = new Articlesearch (); ' Filtermodel ' = $searchModel, ' layout ' = ' {items}<p class= ' text-right tooltip-demo ' >{pager}</p> ', ' pager ' =>[//' Options ' =>[' class ' = ' hidden ']//off with pagination ' firstpagelabel ' = ' first ', ' prev PageLabel ' + ' Prev ', ' nextpagelabel ' + ' Next ', ' lastpagelabel ' = ' last ', ' columns ' = [/ /[' class ' = ' Yii\grid\serialcolumn '],//serial number starting from 1//Data provider contains the data defined by the simple column//using the data ' ID ' of the Model column, ' username ', [ ' label ' + ' article category ',/* ' attribute ' + ' cid ', generate a tag, click sortable */' value ' = ' cate.cname '], [' label ' = ' release date ', ' forma T ' = = [' Date ', ' php:y-m-d '], ' value ' = ' created_at '],//More complex column data [' label ' = ' cover map ', ' format ' = ' raw ', ' value '    =>function ($m) {return html::img ($m->cover,[' class ' = ' img-circle ', ' width ' = 30]); }], [' Class ' =&Gt         ' Yii\grid\datacolumn ',//because it is the default type, you can omit ' value ' = function ($data) {return $data->name;      If the array data is $data [' name '], for example, the case of using Sqldataprovider. },], [' class ' = ' Yii\grid\actioncolumn ', ' header ' = ' action ', ' template ' = ' {delete} ' {update} ',///only need to show delete and update/* ' headeroptions ' = [' width ' = ' + '],*/' buttons ' = ' + ' = ' delete ' = function ($ur L, $model, $key) {return html::a (' <i class= ' glyphicon glyphicon-trash ' ></i> delete ', [' Art Del ', ' id ' = ' + $key], [' class ' = ' btn btn-default btn-xs ', ' data ' = [' Confirm ' =&gt ; ' Are you sure you want to delete the article?       ',]               ]);               }, ' Update ' = function ($url, $model, $key) {return html::a (' <i class= "fa fa-file" ></i> update ",       [' Artedit ', ' id ' = ' $key], [' class ' = ' btn btn-default btn-xs ']); },      ],     ],  ],]);? >


Third, the search with paging function

    • Create a search model (previously done)

    • Controlling incoming data

    • The view displays the controller code:

<?phppublic function Actionindex () {$searchModel = new Articlesearch (); $dataProvider = $searchModel->search (Yii: : $app->request->queryparams);   return $this->render (' index ', [    ' searchmodel ' = ' = ' $searchModel,    ' dataprovider ' + $dataProvider,  ]); }?>


View:

<?php $form = Activeform::begin ([' action ' = ' = ' index '], ' method ' = ' ge ' T ', ' id ' = ' cateadd-form ', ' options ' = [' class ' = ' Form-horizontal '],?> <?= $form Field ($searchModel, ' title ', [' Options ' =>[' class ' + '], ' inputoptions ' = [' placeholder ' = ' article Search ', ' class ' = = ' Input-sm Form-control '],]->label (false)?> <?= Html::submitbutton (' go! ', [' class ' = ' btn btn-sm BT          N-primary '])? ><?php activeform::end ();? ><?= gridview::widget ([' dataprovider ' = $dataProvider,            ' Layout ' = ' {items}<p class= ' text-right tooltip-demo ' >{pager}</p> ', ' pager ' =>[ ' Options ' =>[' class ' = ' hidden ']//closed with pagination ' firstpagelabel ' + ' first ', ' Prevpagelabel ' => ;' Prev ', ' nextpagelabel ' = ' Next ', ' lastpagelabel ' = ' last ',],//This part is the same as the page above 


Related recommendations:

YII implementation of model add default value method

The multi-level linkage drop-down menu implemented by Yii

Yii2 implement form upload file function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.