Question

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

Was it helpful?

Solution 2

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));
    }
}

OTHER TIPS

On CakePHP 3.4 I have this solution:

$page  = (!empty($this->request->query['pagina']) ? $this->request->query['pagina'] : 1);
    $this->paginate = ['page' => $page, 'limit' => '10'];

    try {

        $products = $this->paginate($products);

    } catch (NotFoundException $e) {

        $this->paginate = ['page' => $page-1, 'limit' => '10'];
        $products = $this->paginate($products);

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top