如何让cakephp paginator转到最后一页,当用户输入的页码大于max page(溢出)时?

时间:2013-10-07 04:42:11

标签: cakephp

假设我有21条记录

我的观点显示每页10条记录

现在我在页面上:3,然后我删除了一条记录并刷新页面

蛋糕将显示未找到错误

如何转到第2页(最后一页),而不是显示错误消息?


我检查了PaginatorComponent.php 它只是抛出一个NotFoundException

if ($requestedPage > $page) {
            throw new NotFoundException();
        }

4 个答案:

答案 0 :(得分:1)

根据Manual,您必须捕获异常并重定向到右侧页面

答案 1 :(得分:0)

虽然我不一定对此感到满意,但这是我的所作所为。

    try {
        $this->Paginator->settings = $this->paginate;
        $widgets = $this->paginate();
    } catch (NotFoundException $e) {
        //Redirect to previous page
        $query = $this->request->query;
        $query['page']--;
        extract(Router::parse($this->request->here)); 
        $pass = empty($pass) ? '' : $pass[0]; 
        $this->redirect(array_merge(array('action' => $action, $pass), array('?' => $query))); 
    }

正如您所看到的,我在查询字符串中递减页码并保持重定向,直到我到达有效页面。我无法找到直接到最后一页的已知页数。此外,我不满意提取URL的部分只是为了重建它。在我的情况下,$ pass参数可能存在也可能不存在,这就是我进行空检查的原因。虽然这有效,但我欢迎有关如何做得更好的想法。

答案 2 :(得分:0)

我所做的是在捕获NoFoundException时获取上一页,但是通过命名的params:

try {
    $records = $this->Paginator->paginate();
} catch (NotFoundException $e) {
    $this->request->params['named']['page']--;
    $records = $this->Paginator->paginate();
}

我认为最好只覆盖paginator组件。

答案 3 :(得分:0)

这有效:

```的PHP class PaginatorComponent扩展了CorePaginatorComponent {

/**
 * Overwrite to always redirect from out of bounds to last page of paginated collection.
 * If pageCount not available, then use first page.
 *
 * @param \Cake\Datasource\RepositoryInterface|\Cake\Datasource\QueryInterface $object The table or query to paginate.
 * @param array $settings The settings/configuration used for pagination.
 *
 * @throws \Cake\Network\Exception\NotFoundException
 *
 * @return \Cake\Datasource\ResultSetInterface Query results
 */
public function paginate($object, array $settings = [])
{
    try {
        $resultSet = parent::paginate($object, $settings);
    } catch (NotFoundException $exception) {
        $query = null;
        if ($object instanceof QueryInterface) {
            $query = $object;
            $object = $query->repository();
        }
        $alias = $object->alias();
        $lastPage = $this->request->params['paging'][$alias]['pageCount'] > 1 ? $this->request->params['paging'][$alias]['pageCount'] : null;

        $response = $this->getController()->redirect(['?' => ['page' => $lastPage] + $this->request->getQuery()]);

        // To be please PHPCS and tests, cannot be reached in production.
        if (PHP_SAPI === 'cli') {
            throw new NotFoundException('Redirect to ' . $response->getHeaderLine('Location') . ' for non-CLI.');
        } else {
            $response->send();
        }

        exit();
    }

    return $resultSet;
}

} ```

只需将其放入您的项目中,它将自动使用而不是核心项目。 适用于< = 3.4(第一页)和3.5+(最后一页)。