Reputation: 660
I have created my own object/index action in a yii rest controller which does some simple things:
public function actionIndex($name){
$query = Object::find();
$count = $query->count();
$pagination = new Pagination(['totalCount'=>$count]);
$objectList = $query->offset($pagination->offset)->limit($pagination->limit)->all();
return $objectList;
}
When I make a request to: http://localhost:8443/v0/objects?name=warehouse&page=1&per-page=1 I receive the following response:
[
{
"id": 2,
"data": {
"city": "Test",
"name": "ABC Warehouse",
"postal_code": "M1F 4F2",
"street_address": "1234 Street",
"owner": 76,
"created_at": "2016-09-23 15:10:20",
"updated_at": "2017-07-27 11:56:15",
"created_by": 9,
"updated_by": 13
},
"displayData": []
}
]
I would like to include the pagination link information as shown here but am not sure how to go about this http://www.yiiframework.com/doc-2.0/guide-rest-quick-start.html
HTTP/1.1 200 OK
...
X-Pagination-Total-Count: 1000
X-Pagination-Page-Count: 50
X-Pagination-Current-Page: 1
X-Pagination-Per-Page: 20
Link: <http://localhost/users?page=1>; rel=self,
<http://localhost/users?page=2>; rel=next,
<http://localhost/users?page=50>; rel=last
Upvotes: 2
Views: 1728
Reputation: 900
I assume you're using the yii\rest\ActiveController
A quick look into the yii2 source suggests (to me) that whatever is returned need to implement the yii\data\DataProviderInterface. Right now your code does not return the Pagination object at all to be handled.
Assuming you're Object extends ActiveRecord, try this in your action...
public function actionIndex($name){
$query = Object::find(); // Assumes Object extends ActiveRecord
$countQuery = clone $query; // Good idea to clone query
$count = $countQuery->count();
$pagination = new Pagination(['totalCount'=>$count]);
$query->offset($pagination->offset)->limit($pagination->limit);
return new ActiveDataProvider([
'query' => $query,
'pagination' => $pagination,
]);
}
Note, this code is NOT tested. Hopefully it will help anyway.
--- Edit ---
Also in the yii\rest\ActiveController set this property (as suggested by Scott)
public $serializer = [
'class' => 'yii\rest\Serializer',
'collectionEnvelope' => 'items',
];
Upvotes: 4