Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 activeDataProvider pagination and additional data

Tags:

rest

php

yii

yii2

I am building an API but am stuck trying to add additional data to a result set.

I am using ActiveDataProvider in a class that extends from ActiveControler to get and return the result set is JSON. It works so well and includes the pagination headers without any work required.

$provider = new \yii\data\ActiveDataProvider([
    'query' => Message::find()->where(['location_id' => $id])
]);

return $provider;

However if I get the results first so that I can add new values, the pagination headers are no longer sent back to the client.

$provider = new \yii\data\ActiveDataProvider([
    'query' => Message::find()->where(['location_id' => $id])
]);

$messages['messages'] = $provider->getModels();
$messages['additional_stuff'] = ['field1' => 'foo', 'field2' => 'bar'];
return $messages;

An example of what I might want the output to look like could be:

{
    "messages": [
      {
        "id": "1",
        "content": "message 1"
      },
      {
        "id": "2",
        "content": "message 2"
      },
     ],
     "additional_stuff": {
         "field1": "foo",
         "field2": "bar"
     }
}

What can I do here to add additional values but ensure that the pagination headers are sent?

EDIT:

Thanks to devOp's response I was able to add the headers as required. My action now looks like this:

$provider = new \yii\data\ActiveDataProvider([
    'query' => Message::find()->where(['location_id' => $id])
]);

$messages['messages'] = $provider->getModels();
$messages['additional_stuff'] = ['field1' => 'foo', 'field2' => 'bar'];

$this->sendPaginationHeaders($provider->getHeaders());

return $messages;

Which calls in my new method:

protected function sendPaginationHeaders($pagination)
{
    $pageCount = $pagination->totalCount <= $pagination->getPageSize() ? 1 : ceil($pagination->totalCount / $pagination->getPageSize());

    header('X-Pagination-Current-Page: '. $pagination->getPage());
    header('X-Pagination-Page-Count: '. $pageCount);
    header('X-Pagination-Per-Page: '. $pagination->getPageSize());
    header('X-Pagination-Total-Count: '. $pagination->totalCount);
}

Which adds the standard Yii2 pagination headers. Unfortunately getHeaders() didn't give me the Page-Count but it's easy to calculate that from the others.

like image 824
Dubby Avatar asked Nov 26 '25 07:11

Dubby


1 Answers

You can add the pagination headers by yourself to the resulting array by calling getPagination()">$provider->getPagination(). Here is the documentation of the Pagination-Object: http://www.yiiframework.com/doc-2.0/yii-data-pagination.html

like image 105
devOp Avatar answered Nov 28 '25 22:11

devOp