Quantcast
Channel: Live News for Yii Framework
Viewing all articles
Browse latest Browse all 2941

[Wiki] Building a search GET request with scenarios ; calling a SearchModel from URLs...

$
0
0

Search Models are a very elegant and powerful way to build an Active Data Provider. If you use them a lot, you'll quickly need to use scenarios, which will lead you to a very DRY Controller code.

Doing so, you'll maybe want to call one of your scenarios from URL, and to parse him variables from URL, like : index.php?r=mycont/myaction&scenario=MY_SCENARIO&variable=...

The scenario could be also defined inside the controller. But the important part here, is that a variable you want to use inside a specific scenario is defined in the URL.

But if you do it in the usual way in the controller, parsing the request directly to the search model, you'll have an error, like an SQL error, saying that variable is not defined.

This come from the yii\base\Model::load() function, wich wait for a post request coming from a Form, rather than a Get request coming from an URL.

To handle that : you must give you GET request inside an array to the searchModel, with a key having the name of your Search Model (so has would do a Form).

Let's say that you're using a itemSearch model, inside myactions methods from myController, and that you call it thanks the URL : index.php?r=mycont/myaction&scenario=MY_SCENARIO&param=my_parameter

$searchModel = new ItemSearch();
 
        // $scenario is built thanks the url parameter
    $searchModel->scenario = $this->_getScenario; 
 
        // We get the params from 
    $getParams = Yii::$app->request->queryParams;
 
        // HERE THE TIP : you must put your params request inside a table, and name    its key with the name of the search model
        $params["PostSearch"]    = $getParams; 
 
        $dataProvider = $searchModel->search($params);

Inside the Search Model, do as usual :

....
   public $param
 
   public function rules()
    {
        return [
                 ...
                 // Everything is a string in a URL...
                 [['param'], 'string', 'on' => 'MY_SCENARIO'],
               ]

And that's all. Now, inside the search function, you will have access to $this->param to do what you want.

Also, be careful, you must NOT use quotes inside the url to define scenario. Eg : (WRONG :) index.php?r=mycont/myaction&scenario="MY_SCENARIO"&param=my_parameter


Viewing all articles
Browse latest Browse all 2941

Trending Articles