I’m building a search page that will have many different search parameters that the user can click on, which will pass the variables in the URL.
$this->Restaurant->recursive = 1;
$this->paginate = array(
'conditions' => array(
'City.name' => $this->params['url']['city'],
'Cuisine.name' => $this->params['url']['cuisine'],
),
);
$data = $this->paginate('Restaurant');
$this->set('data', $data);
This works just fine IF there is ?city=newyork&cuisine=pizza in the URL – but if not, it errors out* If it were normal PHP, I’d build out the query as a string and append conditions only if the variables existed…etc. But with Cake I’m not sure where to begin or what would be the best way to manage this.
EDIT:
*If I do not have ‘city’ or ‘cuisine’ being passed as URL variables, I get this:
<b>Notice</b> (8)</a>: Undefined index: city [<b>APP/controllers
/restaurants_controller.php</b>, line <b>18</b>
...
City.name' => $this->params['url']['city'],
</span></code></span></pre></div><pre class="stack-trace">
RestaurantsController::search() - APP/controllers/restaurants_controller.php
, line 18
Dispatcher::_invoke() - CORE/cake/dispatcher.php, line 204
Dispatcher::dispatch() - CORE/cake/dispatcher.php, line 171
[main] - APP/webroot/index.php, line 83
It wouldn’t be a problem if I just had “city” and “cuisine” – but if I plan on having 20 more search options to be passed in the same way, I’d like to be able to pass them or not at my discretion instead of being forced to have them ALL in the URL every time.
What do you mean
errors out?Usually adding
$this->Paginator->options(array('url' => $this->passedArgs));before your pagination call in the view will make cake add all the passed URL params to the url that it generatesEDIT
What you’re looking for are named parameters : http://book.cakephp.org/view/947/Named-parameters
If you look at the last example, you’ll see that the route maps to
ContentsController->view();with all the parameters you (optionally) chose to send available in thepassedArgsarray.EDIT 2
Your problem here is that you have a variable set of search criteria. Your system should basically go through the search criteria and build your search query depending what filters have been chosen. There are several ways you can solve this. The easiest would be to loop through them.
This way, you’re whitelisting a set of filters that can be applied. And you loop through the params and build your
conditionsarray. You’ll have to modify this a bit if you need OR conditions or different MYSQL. But this will allow you to have a variable number of filters.