3

I had been working on a project and stuck in a problem where a view needs two pagination on same model with different conditions in Cakephp 3.

For eg. opened and closed support tickets listing on the same view.

The following is my code. Can someone help me?

//Opened status pagination
$opened_paginate = [
    'contain' => ['Comments'],
    'conditions' => [
        'AND' => ['SupportTickets.status' => '1']
    ],
    'order' => ['SupportTickets.id' => 'DESC'], 
    'limit' => 1
];   

// Closed status pagination  
$closed_paginate = [
    'contain' => ['Comments'],
    'conditions' => [
        'AND' => ['SupportTickets.status' => '2']
    ],
    'order' => ['SupportTickets.id' => 'DESC'],
    'limit' => 1
];                  

$this->set('opened', $this->Paginator->paginate(
    $this->SupportTickets->find(),
    $opened_paginate
));
$this->set('closed', $this->Paginator->paginate(
    $this->SupportTickets->find(),
    $closed_paginate
)); 
Sehdev
  • 5,486
  • 3
  • 11
  • 34
  • Were you planning on having a shared pagination on the view? As `opened` and `closed` are likely to have a different number of pages this is likely to cause issues. It would probably be better to use AJAX to make paging requests for each. – drmonkeyninja May 02 '17 at 09:24

2 Answers2

1

You can paginate different models in a single action (see the docs), but I don’t think this works out on the same model.

Maybe you could build some weird stuff by using Traits or this and that, but I would recommend to rethink what you are trying to do and eliminate the need for paginating the same model in a single view multiple times.

You can paginate multiple models in a single controller action, using the scope option both in the controller’s $paginate property and in the call to the paginate() method:

// Paginate property
public $paginate = [
    'Articles' => ['scope' => 'article'],
    'Tags' => ['scope' => 'tag']
];

// In a controller action
$articles = $this->paginate($this->Articles, ['scope' => 'article']);
$tags = $this->paginate($this->Tags, ['scope' => 'tag']);
$this->set(compact('articles', 'tags'));
Marijan
  • 1,825
  • 1
  • 13
  • 18
0

here i found an answer. https://www.ammann.info/cakephp-3-paginating-model-multiple-times-in-the-same-view/

In the controller:

$this->loadModel('Members');
$paginator1 = $this->paginate(
    $this->Members->find()->where(['tag' => 1]), [
    'model' => 'Members',
    'scope' => 'scope1'
    ]
);

eval('namespace App\Model\Table;'
        . 'class Members2 extends \App\Model\Table\Members {}');
$this->loadModel('Members2');
$paginator2 = $this->paginate(
    $this->Members2->find()->where(['tag' => 2]), [
    'model' => 'Members2',
    'scope' => 'scope2'
    ]
);

In the view:

// first paginator
echo $this->Paginator->sort('title', ['model' => 'Members']);
// second paginator
echo $this->Paginator->sort('title', ['model' => 'Members2']);