Paginator(从Cake 1.3迁移到2.0)

时间:2012-11-22 15:32:39

标签: pagination migration cakephp-2.0

我正在与Cakephp 2.0中的分页器挣扎。当我尝试将我的应用程序迁移到2.0时,我无法找到任何解决方案直接跳转到最后一页。在1.3中,从外面这样做很安静:

echo $this->Html->link(__('Flights'), array('controller' => 'flights',
    'action' => 'index','page' => 'last'));

但是将'page:last'放入的这个小技巧在2.0中不再起作用了。当然有一个名为last的Paginator函数,但这只有在我已经在应用程序中时才有用。我的问题是直接从外部链接访问分页器的最后一页。

3 个答案:

答案 0 :(得分:0)

这是一种简单的方法:

echo  $this->Paginator->last('Any text');

获取最后一页数字的其他方法是:

echo  $this->Paginator->counter(array('format' => '{:pages}'));

然后您可以使用它来生成链接。

欲了解更多信息: http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::last

答案 1 :(得分:0)

在为这个问题创建赏金后不久,我找到了使用CakePHP 2.2.4解决MY问题的方法。我试图完成相同的任务,而是使用版本2.2.4而不是2.0。基本上,如果我有一个看起来像http://www.domain.com/articles/page:last的链接,那么控制器的分页方法就会知道要去哪个页面并显示该页面的正确结果(文章)。例如,如果我有110篇文章并且分页限制设置为25,则通过转到该URL,它将显示第5页的第5页,显示记录101-110。如果我去“page:first”,我也想要相同的功能。

我需要更改我的库文件 lib / Cake / Controller / Component / PaginatorComponent.php

我改变了

if (intval($page) < 1) {
    $page = 1;
}

if ((intval($page) < 1 && $page != "last") || $page == "first") {
    $page = 1;
}

我还添加了

if($page == "last"){
    $page = $pageCount;
}

行后

$pageCount = intval(ceil($count / $limit));

Christian Waschke,使用此解决方案,您可以使用与您在问题中编写的相同的链接助手。对我来说,链接帮助器看起来像这样

<?php echo $this->Html->link('Go to Last Page', array('controller' => 'articles', 'action' => 'index', 'page' => 'last')); ?>

答案 2 :(得分:0)

如果'last'作为页码传递,您可以自己'计算'最后一页;

不鼓励在CakePHP库文件中进行修改,因为这将使将来很难进行升级。

基本上,PaginatorHelper使用由PaginatorComponent计算和设置的viewVars,如下所示:https://github.com/cakephp/cakephp/blob/master/lib/Cake/Controller/Component/PaginatorComponent.php#L212

您可以在行动中复制此内容;例如:

public function index()
{
    if (!empty($this->request->params['named']['page'])) {
        switch($this->request->params['named']['page']) {
           case 'first':
                // replace the 'last' with actual number of the first page
                $this->request->params['named']['page'] = 1;
                break;

           case 'last':
                // calculate the last page
                $limit = 10; // your limit here
                $count = $this->Flight->find('count');
                $pageCount = intval(ceil($count / $limit));

                // replace the 'last' with actual number of the last page
                $this->request->params['named']['page'] = $pageCount;
                break;
        }

    }

    // then, paginate as usual
    $this->set('data', $this->paginate('Flight'));
}

为了改善这一点,应将此逻辑移至单独的方法或行为。然而;如上所示,在PaginatorComponent中进行修改需要

另请注意,我的示例中的'find(count)'不采取其他条件,如果需要,应添加它们

如果您查看paginate()的CakePHP 1.3来源,则上述代码具有可比性; https://github.com/cakephp/cakephp/blob/1.3/cake/libs/controller/controller.php#L1204