sandeep
sandeep

Reputation: 2892

Cakephp search option with multiple fields

In my project i have implement search option. Where we user should have to capability to search based on four fields namely "Zip, Street, City and State". But none of these fields are mandatory.

I am confused with what conditions should i place in find(). So please help me.

Upvotes: 0

Views: 3249

Answers (3)

RabidFire
RabidFire

Reputation: 6340

I'm assuming that you're having trouble because the form fields are optional, and you're not sure how to build the conditions for your find. Here's a simple way:

$conditions = array();
if (!empty($this->data['User']['zip'])) {
    $conditions[] = array('User.zip' => $this->data['User']['zip']);
}
if (!empty($this->data['User']['street'])) {
    $conditions[] = array("User.street LIKE '%{$this->data['User']['street']}%'");
}
... etc

Finally, you can append the conditions either strictly:

$this->User->find('all', array('conditions' => $conditions));

Or, loosely:

$this->User->find('all', array('conditions' => array('or' => $conditions)));

The second form places the OR operand between your WHERE conditions so that it returns any particular match. Start off here and increase the complexity of the search slowly.

Upvotes: 2

JayD3e
JayD3e

Reputation: 2217

This is the correct way to handle a search in CakePHP, or any web application for that matter: http://bakery.cakephp.org/articles/calin/2008/09/18/search-feature-to-cakephp-blog-example.

It involves creating a Search Index, which essentially means that it rolls all of the fields of each record in a table into a single string, which makes it much easier to search. Follow the above tutorial to optimize searching on your site.

Upvotes: 0

pawelmysior
pawelmysior

Reputation: 3250

You will have to be more specific on what the problem is. If it's just putting the conditions, then basically try something like this:

<?php
$results = $this->Model->find('all', array(
  'conditions' => array(
    'Model.field' => '%'.$this->data['Model']['some_search_field'].'%',
    'Model.field2' => '%'.$this->data['Model']['some_search_field2'].'%')
  ));
?>

Upvotes: 1

Related Questions