Using CakeDC's search plugin to search data with multi-select field

823 views Asked by At

I am trying to implement a search with CakeDC's Search plugin. In this search I have a field which has 'multiple' => 'checkbox' is set. This field allows user to select multiple cities so that they can filter results according to city/cities. What I did in favour to this, I simply specified the 'type' => 'IN' for that field in Searchable Model's $filterArgs. But noting happened it just responded with all result no searching/filtration happened. To get the clear picture of what I have implemented here are the code snippets:

Model.php

   public $actsAs = array(
            'Search.Searchable'
        );
   public $filterArgs = array(
                    'city' => array(
                        'type' => 'in',
                        'field' => 'Model.city'
                    ));

search_form.ctp

echo $this->Form->create('Model', array('url' => array('controller' => 'models', 'action' => 'search')));
echo $this->Form->input('city', array(
    'multiple' => 'checkbox',
    'options' => array(
        'city1' => 'city1',
        'city2' => 'city2',
        'cityn' => 'cityn')
));
echo $this->Form->end('search');   

ModelsController.php

public function search() {
        $this->layout = 'front_common';
        $this->Prg->commonProcess();
        $this->Paginator->settings = array(
            'conditions' => $this->Model->parseCriteria($this->Prg->parsedParams()),
            'limit' => 10
        );
        $this->set('Data', $this->Paginator->paginate());
}

also once I tried to use a beforeFilter() in ModelsController to implode the city array() with (,) to be used with IN but same all results. I want to ask if there is any other plugin to do this or any hack to do this with cakeDC's search plugin. Please help.

1

There are 1 answers

0
zeroasterisk On

This should work fine, assuming you are passing in the arg to parseCriteria() as a simple array of values.

public $filterArgs = array(
    array(
        'name' => 'city',
        'type' => 'value',
        'field' => 'Model.city'
    )
);

And you should be able to pass city:houston|dallas|austin in the URL

It should parse that into an array of args => [city => [houston, dallas, austin]]

And parseCriteria() will translate that into the following conditions fragment: [Model.city => [houston, dallas, austin]]

And CakePHP natively translates that into a SQL where fragment: IN(houston, dallas, austin)

Use DebugKit and monitor your SQL... you can debug() at any step of the process, you should get these values.

Here's the full docs on the Search plugin: https://github.com/CakeDC/search/tree/master/Docs/Documentation

(I use it heavily, and I love how it lets me organize all search filters)