之前光是要產生資料列表,還有分頁,都很麻煩。
要先查出這頁要顯示的資料,然後還要計算所有的資料筆數
才能計算出總頁數,進而產生出 分頁 Bar。
現在有了 Zend_Paginator 就超方便的了,
簡簡單單就可以把所有事情搞定。
現在來個 Sample 吧。可以參考 Chapter 39. Zend_Paginator
首先在 application/Bootstrap.php,我加了一個 _initRouter
主要用來將某些 Request ,導到對應的 Controller。
// application/Bootstrap.php
/**
* 設定 routing rules
* @author chingwei
*/
protected function _initRouter() {
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$router->addRoute('media_user',
new Zend_Controller_Router_Route_Regex(
'_user/([\w\-\.]+)\*{0,1}(\d*)\/{0,1}$',
array('controller' => 'ching', 'action' => 'user'),
array(1 => 'viewId', 2 => 'page'),
'_user/%s*%d'
)
);
}
接著在 Controller 裡將所有的資料產生出來,然後交給 Zend_Paginator
// application/modules/default/controllers/ChingController.php
$allMedia = $mediaModel->getMediaBySn($sn); $paginator = Zend_Paginator::factory($allMedia); $paginator->setCurrentPageNumber($page); $paginator->setItemCountPerPage(3); $this->view->paginator = $paginator;
然後在 View 中,下面中前面的程式碼就是產生最上面那張圖中的三個項目。
然後後面的Code 是指定要用那個樣版來產生分頁 Bar
// application/modules/default/views/ching/test.phtml
<? if (count($this->paginator)): ?>
<ul>
<? foreach ($this->paginator as $item): ?>
<li><?= $item['TITLE']; ?></li>
<? endforeach; ?>
</ul>
<? endif; ?>
<?= $this->paginationControl($this->paginator,
'Sliding',
'/ching/_pagination.phtml'); ?>
最後面這個就是分頁樣版了
// application/modules/default/views/ching/_pagination.phtml
<? if ($this->pageCount): ?>
<div class="paginationControl">
<!-- Previous page link -->
<? if (isset($this->previous)): ?>
<a href="<?= $this->url(array('page' => $this->previous)); ?>">
< Previous
</a> |
<? else: ?>
<span class="disabled">< Previous</span> |
<? endif; ?>
<!-- Numbered page links -->
<? foreach ($this->pagesInRange as $page): ?>
<? if ($page != $this->current): ?>
<a href="<?= $this->url(array('page' => $page)); ?>">
<?= $page; ?>
</a> |
<? else: ?>
<?= $page; ?> |
<? endif; ?>
<? endforeach; ?>
<!-- Next page link -->
<? if (isset($this->next)): ?>
<a href="<?= $this->url(array('page' => $this->next)); ?>">
Next >
</a>
<? else: ?>
<span class="disabled">Next ></span>
<? endif; ?>
</div>
<? endif; ?>
以上~搞定!
沒有留言:
張貼留言