Hy. I have a ProductController which extends the yii\rest\ActiveController. Question is that how can i make querys via HTTP GET request.
Like: http://api.test.loc/v1/products/search?name=iphone
And the return object will contains all products with name iphone.
In Config/web.php -> Add 'extraPatterns' => ['GET search' => 'search']
**In Rest Api Controller :- Moduels/v1/controllers/ **
basicinfo :- Is your controller Name , Name and age is your Fields Name.you can add all parameters exist in your table.
Search URL LIKE :- basicinfo/search?name=yogi&age=12-23
Include use yii\data\ActiveDataProvider;
I would not recommend to use Superglobals $_GET directly . Instead you can use Yii::$app->request->get().
Following is the example how you can create a generic search action and use it in the controller.
At the controller End
Custom Search Action
Ok i figured out, just put this in your Controller and modifiy the URL router in config.
And the URL rule (edit)
UPDATE: Apr 29 2016
This is one more approach simpler than the one I introduced in the previous update. It is always about involving the Search class generated by gii. I like using it to define and maintain all the search related logic in a single place like using custom scenarios, handle validations, or involve related models on the filtering process (like in this example). So I'm going back to my first answer :
Then be sure that your search class is using
load($params,'')
instead ofload($params)
or alternatively add this to the model class:That should be enough to have your requests looking like:
/products?name=iphone&status=available&sort=name,-price
UPDATE: Sep 23 2015
This is the same approach but by implementing a complete & cleaner solution :
Now your GET request will look like :
/products?name=iphone
Or even like :
/products?name=iphone&status=available&sort=name,-price
Note:
If instead of
/products?name=iphone
you are looking for a specific action to handle searching or filtering requests like :/products/search?name=iphone
Then, in the code above you'll need to remove the actions function with all its content :
rename :
indexDataProvider()
toactionSearch()
& finally add
'extraPatterns' => ['GET search' => 'search']
to your yii\web\UrlManager::rules as described in @KedvesHunor's answer.Original answer: May 31 2015
There is a short way to do this, if when using Gii to generate CRUD for your model, you defined a Search Model Class, then you can use it to filter results, all you have to do is to override the
prepareDataProvider
function ofindexAction
to force it return theActiveDataProvider
instance returned by thesearch
function of your model search class rather than creating a custom new one.To resume if your model is Product.php & you generated a ProductSearch.php as a search class to it, then in your Controller you just need to add this :
Then to filter results, your url may look like this :
or even like this :