首頁  >  文章  >  後端開發  >  yii2實現分頁和搜尋的分頁功能

yii2實現分頁和搜尋的分頁功能

不言
不言原創
2018-06-15 16:30:173622瀏覽

本篇文章主要介紹了yii2實現分頁,帶有搜尋的分頁功能範例,具有一定的參考價值,有興趣的小夥伴們可以參考一下。

一、模型配置

例子會用到三個models。文章類別表和文章表用gii生成下即可,最後一個是搜尋驗證模型。其中,只講下一個聯表和搜尋驗證。其他不用操作。

1.文章表關聯

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

#2.搜尋模型

common/models/search/建立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;
  }
}

二、分頁使用

##首先在控制器的動作中,建立分頁物件並且為其填充資料:

<?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,
    ]);
  }
?>

其次在檢視中我們輸出的範本為目前頁並透過分頁物件連結到該頁:

<?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;,
]);
?>

#方式二

    控制器:
  • <?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
        ]);
    ?>
  • 」檢視:

  • <?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;]);
           },
          ],
         ],
      ],
    ]);
    ?>

#三、搜尋帶分頁功能



##################################################################### ###########建立搜尋模型(前面己做)############控制傳入資料############檢視顯示控制器程式碼:###############
<?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,
  ]);
 }
?>
##########「檢視:#########
<?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;,
          ],
       //这部分和上面的分页是一样的
#########以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網! ######相關推薦:#########關於YII框架中搜尋分頁jQuery寫法###############Yii使用CLinkPager進行的分頁### #########################

以上是yii2實現分頁和搜尋的分頁功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn