0

假设我有 21 条记录

我的视图显示每页 10 条记录

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

cake 将显示未找到错误

我怎样才能转到第 2 页(最后一页),而不是显示错误消息?


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

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

4 回答 4

1

根据手册,您必须捕获异常并重定向到正确的页面

于 2013-10-07T06:15:41.557 回答
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 参数可能存在也可能不存在,这就是我进行空检查的原因。尽管这可行,但我欢迎有关如何做得更好的想法。

于 2014-05-18T11:37:41.850 回答
0

这有效:

```php 类 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+(最后一页)。

于 2017-09-28T17:42:09.027 回答
0

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

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

不过,我认为最好只覆盖分页器组件。

于 2017-09-28T17:15:35.907 回答