CakePHP 3如何使用next和prev for view action

时间:2015-09-13 18:46:59

标签: cakephp cakephp-3.0

我正在尝试在CustomersController的视图页面中集成next和prev按钮。在我的下一个按钮中,我正在尝试添加一个链接,该链接将从表中获取下一条记录。对于从表中获得前一记录的prev相同。我尝试了下面的分页,但是当我点击下一步时,它会转到http://localhost/path/customers/view/1?page=2链接,我想找到它会带我到下一个记录http://localhost/path/customers/view/2

// Shows the page numbers
<?= $this->Paginator->numbers() ?>

// Shows the next and previous links
<?= $this->Paginator->prev('« Previous') ?>
<?= $this->Paginator->next('Next »') ?>

// Prints X of Y, where X is current page and Y is number of pages
<?= $this->Paginator->counter() ?>

我也试过这个<?= $this->Paginator->numbers(['first' => 2, 'last' => 2]); ?>

1 个答案:

答案 0 :(得分:0)

我们可以使用foreach代替next and prev

public function view($id = null)
{
    $ids = Cache::read('items_ids');
    if (empty($ids)) {
        $ids = $this->Items->find('list')->toArray();
        Cache::write('items_ids', $ids);
    }
    /*
     * $ids here must be something like this:

     Array
        (
            ............
            [GS00001] => Item 1
            [GS00003] => Item 2
            ..........
        )

    */
    //pr($ids);die; //this for debug


    //seek to the item with id = $id
    $found = $next = $prev = false;
    foreach ($ids as $key => $value) {
        //pr($key);
        if($found){
            $next = [
                'id'   => $key,
                'name' => $value
            ];
            break;
        }
        if ($key == $id) {
            $found = true;
        } else {
            $prev = [
                'id'   => $key,
                'name' => $value
            ];
        }
    }
    //pr(compact(['next','prev']));die;
    /*

    $next and $prev here:

    If first:
    Array
    (
        [next] => false
        [prev] => Array
            (
                [id] => GS00264
                [name] => Last Item
            )

    )

    If last:
    Array
    (
        [next] => Array
            (
                [id] => GS00003
                [name] => First Item
            )

        [prev] => false
    )

     * */


    $item = $this->Items->get($id, [
        'contain' => ['MenuGroups', 'Orders']
    ]);
    $this->set(compact(['item', 'next', 'prev', 'ids']));
    $this->set('_serialize', ['item', 'next', 'prev', 'ids']);
}