over 3 years ago

YiiCLinkPager 跟 Railswill_paginate 一樣有提供分頁功能,先介紹簡單的覆寫,之後有空在詳細介紹,寫起來的感覺,小弟是認為Yii比較好覆寫的說XDD。

自己寫一支 MyLinkPager 繼承 CLinkPager 放在 components,然侯覆寫 runcreatePageButton,就很夠用了,當然還有其他method可以覆寫,剩下的就用參數帶進去吃就好

controller
<?php
public function actionClinkPager()
{
    // CDbCriteria 條件設定

    $projects = Project::model();
    $criteria = new CDbCriteria;
    $criteria->select = 'id, name';
    $criteria->addCondition('status =:status');
    $criteria->params = array('status' => 1);
    
    // 分頁設定

    $data['pages'] = new CPagination($projects->count($criteria));
    $data['pages']->pageSize = 15;
    $data['pages']->applyLimit($criteria);
    $data['projects'] = $projects->findAll($criteria);
    $this->render('index', $data);
}
protected/views/index.php
<!--列表-->
<?php foreach($projects as $i => $project): ?>
    <?php echo $project->id; ?> : <?php echo $project->name; ?>
    <hr>
<?php endforeach; ?>
  
<!--分頁-->
<?php $this->widget('MyLinkPager',array(
  'pages'=>$pages, 
  'maxButtonCount' => 10,
  'header' => '<table align="center"><tbody><tr><td align="center" height="40" class="page-style">',
  'footer' => '</td></tr></tbody></table>',
  'firstPageLabel' => imgtag('images/firstPageLabel.jpg', '', array(
        'hspace'=>'5',
        'align'=>'absmiddle'
  )),
  'lastPageLabel' => imgtag('images/lastPageLabel.jpg', '', array(
        'hspace'=>'5',
        'align'=>'absmiddle'
  )),
  'prevPageLabel' => imgtag('images/prevPageLabel.jpg', '', array(
        'hspace'=>'5',
        'align'=>'absmiddle'
  )),
  'nextPageLabel' => imgtag('images/nextPageLabel.jpg', '', array(
        'hspace'=>'5',
        'align'=>'absmiddle'
  ))
  
)); ?>
components/widgets/MyLinkPager.php
  <?php
  class MyLinkPager extends CLinkPager
  {
    public function run()
    {
      $this->registerClientScript();
      $buttons=$this->createPageButtons();
      if(empty($buttons))
        return;
      echo $this->header;
      echo implode("\n",$buttons);
      echo $this->footer;
    }
      
    protected function createPageButton($label,$page,$class,$hidden,$selected)
    {
      if($hidden)
        return '';
      elseif($selected)
        return $label;
      else
        return CHtml::link($label,$this->createPageUrl($page));
    }
  }
← Yii create component Yii Debug Mode →