CakePHP - 分頁



如果我們想要顯示一個龐大的資料集,我們可以使用分頁功能,並且 CakePHP 4 中提供了這個功能,非常易於使用。

我們有一個名為“articles”的表格,其中包含以下資料:

Options

讓我們使用分頁功能以頁面的形式顯示資料,而不是將所有資料都一起顯示。

示例

按照以下程式所示修改 config/routes.php 檔案。

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   //$builder->connect('/pages',['controller'=>'Pages','action'=>'display', 'home']);
   $builder->connect('posts',['controller'=>'Posts','action'=>'index']);
   $builder->fallbacks();
});

src/Controller/PostsController.php處建立一個PostsController.php檔案。將以下程式碼複製到控制器檔案中。如果已建立,請忽略。

src/Controller/PostsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   class PostsController extends AppController {
      public function index(){
         $this->loadModel('articles');
         $articles = $this->articles->find('all')->order(['articles.id ASC']);
         $this->set('articles', $this->paginate($articles, ['limit'=> '3']));
      }
   }
?>

使用以下方法獲取 articles 表格中的資料:

$this->loadModel('articles');
$articles = $this->articles->find('all')->order(['articles.id ASC']);

要應用分頁功能,我們將每頁顯示 3 條記錄,操作如下:

$this->set('articles', $this->paginate($articles, ['limit'=> '3']));

這足以啟用 articles 表格上的分頁功能。

src/Template處建立一個名為Posts的目錄,並在該目錄下建立一個名為 index.php 的View檔案。將以下程式碼複製到該檔案中。

src/Template/Posts/index.php

<div>
<?php foreach ($articles as $key=>$article) {?>
<a href="#">
   <div>
   <p><?= $article->title ?> </p>
   <p><?= $article->details ?></p>
   </div>
</a>
<br/>
<?php
}
?>
<ul class="pagination">
<?= $this->Paginator->prev("<<") ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next(">>") ?>
</ul>
</div>

頁碼列表的分頁功能如下所示:

<ul class="pagination">
<?= $this->Paginator->prev("<<") ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next(">>") ?>
</ul>

透過訪問以下 URL 執行以上示例:

https:///cakephp4/posts

輸出

執行程式碼後,您將看到以下輸出:

Article

點選下面的數字切換到下一頁,或使用“下一頁”或“上一頁”按鈕。

例如

Article1

您將看到 page=2 附加到瀏覽器中的頁面 URL。

廣告

© . All rights reserved.