在CakePHP中如何使用分页?

所在分类: Cakephp面试题及答案 查看次数: 493

在CakePHP控制器中,分页组件用于构建分页查询。 为了在视图中生成分页链接和按钮,使用PaginatorHelper

以下是CakePHP中的示例分页使用代码 -

控制器中的分页 -

class PostsController extends AppController
{

    public $paginate = [
        "limit" => 25,
        "order" => [
            "Posts.id" => "desc"]
    ];

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent("Paginator");
        $this->loadHelper("Paginator", ["templates" => "MyPlugin.paginator-templates"]);
    }

    public function display(){
      $this->set("posts", $this->paginate());
    }
}

CakePHP视图中的分页 -

<?php

$paginator = $this->Paginator;

if($posts){

    //creating our table
    echo "<table>";

        // our table header, we can sort the data user the paginator sort() method!
        echo "<tr>";

            // in the sort method, there first parameter is the same as the column name in our table
            // the second parameter is the header label we want to display in the view
            echo "<th>" . $paginator->sort("id", "ID") . "</th>";
            echo "<th>" . $paginator->sort("title", "Title") . "</th>";
            echo "<th>" . $paginator->sort("published_on", "Published on") . "</th>";

        echo "</tr>";

        // loop through the user  records
        foreach( $posts as $post ){
            echo "<tr>";
                echo "<td>{$post["Post"]["id"]} </td>";
                echo "<td>{$post["Post"]["title"]} </td>";
                echo "<td>{$post["Post"]["published_on"]} </td>";

            echo "</tr>";
        }

    echo "</table>";

    // pagination section
    echo "<div class=paging>";

        // the first page button
        echo $paginator->first("First");

        // prev page button, 
        // we can check using the paginator hasPrev() method if ther a previous page
        // save with the 'next' page button
        if($paginator->hasPrev()){
            echo $paginator->prev("Prev");
        }

        // the 'number' page buttons
        echo $paginator->numbers(array("modulus" => 2));

        // for the 'next' button
        if($paginator->hasNext()){
            echo $paginator->next("Next");
        }

        // the 'last' page button
        echo $paginator->last("Last");

    echo "</div>";

}

// tell the user there's no records found
else{
    echo "No posts found.";
}
?>

 完善答案    |    登录 后显示完整答案

注:此试题仅作为相关知识水平测试,不能作为权威试题和答案。非商业转载注明原文链接即可;商业转载需本站授权同意。