Harris
Harris

Reputation: 1138

cakephp 3.3: pagination and sorting error when model is in url

I have the following Events controller:

public $paginate = [
    'sortWhitelist' => ['title', 'id', 'price', 'date', 'Categories.description'],
    'order'         => ['date' => 'desc']
];

and an index method:

$events = $this->Events->find()->contain(['Categories']);
$this->set('events', $this->paginate($events));

In my view file I have a table with echo $this->Paginator->sort('id', 'code') and a

echo $this->Paginator->numbers([
    'separator' => '',
    'currentTag' => 'a',
    'modulus' => 25,
    'currentClass' => 'active',
    'tag' => 'li',
    'first' => 1
]);

If I go to page /events I get the expected results. If I sort by id and click in page 2 the url shows events?page=2&sort=Events.id&direction=asc and the result is not correct.

I see the sql log and no order by clause appears. If I manually edit the url without the model: events?page=2&sort=id&direction=asc the result is correct.

am I doing something wrong or is it a bug?

Thanks

Upvotes: 2

Views: 529

Answers (1)

Reactgular
Reactgular

Reputation: 54821

The sort field is not in your whitelist.

As soon as you configure the sortWhitelist the paginator component rejects all other sort parameters.

The paginator component understands the sort=id query parameter, and will assume you mean the default model for the pagination, but the helper is following the naming convention for sorting parameters. Which includes the model name. The sort=id parameter works because id is in your whitelist.

So you have to include Events in the sortWhitelist

public $paginate = [
    'sortWhitelist' => ['Events.title', 'Events.id', 'Events.price', 'Events.date', 'Categories.description'],
    'order' => ['Events.date' => 'desc']
];

Upvotes: 1

Related Questions