Search code examples
phpsearchcakephpplugins

CakePHP Search Plugin, search for a value equal or higher than the given in the search


I'm using the CakePHP Search Plugin, and there's something I can't get to work. I would like to have a search field (let's call it age) where a user can input a value (like 24, for example) and get as a result all the elements with a value in the age field of the table who have age 24 or higher. How can I do that?

So far I can perform normal searches, like by name or by an exact value (if you want age 24 exactly then it works fine).

Here's the code related with the Search Plugin that I have so far:

- model:

class Person extends AppModel{ 

    var $name = 'Person';
    public $actsAs = array('Searchable');

    public $filterArgs = array(
        array('name' => 'name', 'type' => 'like'),
        array('name' => 'age', 'type' => 'value'),
    );
}

- controller:

class PersonsController extends AppController {

var $name = 'Persons';
var $components = array('Search.Prg'); 
public $presetVars = array(
    array('field' => 'name', 'type' => 'value'),
    array('field' => 'age', 'type' => 'value'),
    );

function index() {
    $this->set('persons', $this->Person->find('all'));
}

/* ---------------- SEARCH PLUGIN --------------*/

public function find() {

    $this->Prg->commonProcess();
    $this->paginate['conditions'] = this->Game->parseCriteria($this->passedArgs);
    $this->set('persons', $this->paginate());
}   
}

- find.ctp:

//apart from the code below, I have all the code to show the results
    echo $form->create('Game', array(
        'url' => array_merge(array('action' => 'find'), $this->params['pass'])
        ));
    echo $form->input('name', array('div' => false));
    echo $form->input('age', array('div' => false));
    echo $form->submit(__('Search', true), array('div' => false));
    echo $form->end();

To sum up: with the code above, I can perfomr a search of an exact value for the age field. How do I change that to perform a search of 'age >= value entered'?

THank you so much in advance!


Solution

  • So this is how I solved it (or at least it seems to work with all the test I've done so far):

    • Changed the 'age' line by the following line in the filterArgs array in the model:

      array('name' => 'age', 'type' => 'query', 'method' => 'findByAge', 'field' => 'Person.age'),
      
    • Added the following method in the same model:

      public function findByAge($data = array()) {
      
          $query = array(
                         'Person.age >='  => $data['age'],
                          );
          return $query;
      }
      

    That's it! With the 'query' type, any complex query can be added to the main query using a method. Thanks to satyrwilder for pointing in the right direction!