6

I setup the default rest api in yii2 and it gives me the list of users when I run "api/web/v1/users" using get method.

Is there any way to sort the output data like "api/web/v1/users?sort=name desc" ?

1
  • I think you should implement it by yourself. Commented Nov 17, 2014 at 11:33

2 Answers 2

13

There is no need to write code for it. Yii already supports inverse sorting by adding a negative sign to attribute name as shown here [Yii core code].

Unless name is not included in your model's safe attributes list, you can just use sort=-name instead of sort=name desc :

api/web/v1/users?sort=-name
  • Note: you can also chain sorting within commas : api/web/v1/users?sort=-name,id,-date

Otherwise if your field is not a safe attribute or when advanced sorting is needed, then you'll have to override IndexAction::prepareDataProvider or configure it to return an activeDataProvider which specifies how your sorting should work.

Sign up to request clarification or add additional context in comments.

1 Comment

note in the data provider sort attribute, you may need to turn multi-sort on via 'enableMultiSort' => true
-2

See https://github.com/githubjeka/yii2-rest/blob/master/rest/versions/v1/controllers/PostController.php#L35

You can use $action->param or $_GET['sort'] for add to sort with dataProvider.

2 Comments

This is bad solution. Better check @SalemOuerdani's anwer. That functionality is built in REST YII2 controller.
SalemOuerdani's answer is about $_GET['sort'] param. It'is same as my answer, but more detailed about $_GET['sort']. If you want to write other params, then you need to use $action->param. And default functionality is build in BaseDataProvider::setSort() , not in Controller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.