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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With