简体   繁体   中英

CakePHP 3: How to use custom pagination?

I don't succeed in using the pagination with a custom query. I follow exactly what's in the doc, but it doesn't work. The point is to paginate a list of records, having the flag 'valid' to 'Y' or 'N'.

In the controller:

if (!isset($this->request->query['valid']) || $this->request->query['valid'] == '')
  $allFilters['valid'] = 'N';
else
  $allFilters['valid'] = 'Y';
$this->paginate = ['finder' => ['curnames' => $allFilters]];
$data = $this->paginate($this->Names)->toArray();

In the model:

public $paginate = ['finder' => 'curnames', 'limit' => 25, 'order' => ['Names.id' => 'asc']];

public function findCurnames(Query $query, array $options) {
  $query->where([
    'valid' => $option['valid']
  ]);
  return $query;
}  

When I execute the code, I get a Cake\\Network\\Exception\\NotFoundException exception. What I am missing?

Update: The version is 3.3. The error is triggered when this is executed:

$data = $this->paginate($this->Names)->toArray();

Update : In the controller, I've change the line

$this->paginate = ['finder' => ['curnames' => $allFilters]];

to

$paginate = ['finder' => ['curnames' => $allFilters]];

and the error doesn't pop up anymore. But the condition filtering on the 'valid'='Y' or 'N' is not taken into account. So it still doesn't work.

I got the answer. The error comes from a typo. Correct code should be

'valid' => $options['valid']

Options with a 's'. Now it works.

Isn't it easier to do something like this (without any custom finder method):

if ($this->request->getQuery('valid', '') == '')
  $valid = 'N';
else
  $valid = 'Y';

$this->paginate = [
  'limit' => 25,
  'order' => ['Names.id' => 'asc']
];
$query = $this->Names->find('all')
  ->where([
    'valid' => $valid
  ]);
$data = $this->paginate($query)->toArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM