cakephppaginatorcakephp-2.4

Out of range page requests


I am a begginer in cakephp, my version is 2.4.3

In document I find sample code below

public function index() {
    try {
        $this->Paginator->paginate();
    } catch (NotFoundException $e) {
        //Do something here like redirecting to first or last page.
        //$this->request->params['paging'] will give you required info.
    }
}

My question :

1.How to redirect to the last page, is there any way to get the total number of pages?

2.I tried to output $this->request->params['paging'] with debug(),but nothing was displayed, just a null value,Did i do anything wrong?

please help me, thinks


Solution

  • The paging data not being available is either a bug, or the documentation is wrong - I'd say it's the former, as it would be kinda redundant to count the records again when the Paginator component already did that.

    Looking at the responsible code:

    https://github.com/cakephp/cakephp/blob/2.4.3/lib/Cake/Controller/Component/PaginatorComponent.php#L215

    shows that the exception is thrown before the paging key is set in the params array. So until this is fixed you'll either have to modify the core, or count and calculate again on your own, something like this (may need some tweaking):

    public function index()
    {
        try
        {
            $this->Paginator->paginate();
        }
        catch(NotFoundException $e)
        {
            extract($this->Paginator->settings);
            $count = $this->ModelName->find('count', compact('conditions'));
            $pageCount = intval(ceil($count / $limit));
            $this->redirect(array('page' => $pageCount));
        }
    }