Cakephp 2.5 search box not working

215 views Asked by At

I am a beginner in CakePHP. I want to do a simple search box, but it is not working, below is the code in my controller:-

public function index() {         
    if ($this->request->is('post')) {
        $this->loadModel('Job');
        $this->request->data = $keyword; 
        $result = $this->Job->find('all', array(
            'condition'=>array('Job.title'=>'% $keyword %')
        ));
        $this->set('rslt',$result); 
        //$this->set('kc',$keyword);
    } 
}

For my view, I have the code below:-

<?php echo $this->Form->create('search', array('type'=>'get'));?>
<?php echo $this->Form->input('search');?>
<?php echo $this->Form->end('Submit');?>    

<pre><?php print_r($rslt) ; ?></pre>

However the search result displays a blank page.

3

There are 3 answers

6
Ahs N On

Change this:

'% $keyword %'

to this:

'%$keyword%'

That is, remove the spaces, else the generated SQL will try to find the keyword surrounded by spaces.

14
drmonkeyninja On

There look to be a few issues with your code.

Firstly, you should be getting your keyword from the request data, e.g. $this->request->data['search']['keyword']. Don't overwrite $this->request->data like in your example code; it is meant to be an array of data submitted to the page, you're replacing this with a string!

Secondly, your condition needs to look something like 'Job.title LIKE' => '%' . $this->request->data['search']['keyword'] . '%'. Using single quotes around a PHP variable treats it as a string so will not replace it with the variable's value. Instead we only quote the %s.

You were also missing the LIKE keyword for the search in the condition index.

The code in your controller should look something like:-

public function index() {         
    if (!empty($this->request->data)) {
        $this->loadModel('Job');
        $result = $this->Job->find('all', array(
            'conditions' => array('Job.title LIKE' => '%' . $this->request->data['search']['keyword'] . '%')
        ));
        $this->set('rslt',$result); 
    } 
}
4
Michel On

You form method is set to "GET" not post as you are trying to access it in your controller.

//Your view code

<?php echo $this->Form->create('search', array('type'=>'get'));?>
<?php echo $this->Form->input('search');?>
<?php echo $this->Form->end('Submit');?>  

You should do this in your controller.

if($this->request->is('get')){
  $keyword = $this->request->data['search'];
// OR $keyword = $_GET['search'];

$this->Job->find('all', array('conditions' => 
  'Job.colunmName LIKE' => '%'.$keyword.'%'
))
}