There are three steps:
1) create a completely normal form with an input field using the HTML helper in your view:
// app/views/foo_bars/search.ctp <?php echo $this->Form->create('FooBar'); echo $this->Form->input('field'); echo $this->Form->end('Submit'); ?>
2) You have jquery autocomplete:
// app/views/foo_bars/search.ctp <?php echo $this->Html->scriptBlock( .'$("#FooBarField").autocomplete({' .'source:"/foo_bars/find",' .'delay: 100,' .'select:function(event,ui){$(this).parent().parent().children("input").val(ui.item.id);},' .'open:function(event,ui){$(this).parent().parent().children("input").val(0);}' .'});' array('inline' => false)); ?>
3) Request the database through the controller to obtain the possible values:
// app/controllers/foo_bars_controller.php <?php public function find() { if ($this->RequestHandler->isAjax()) { $this->autoLayout = false; $this->autoRender = false; $this->FooBar->recursive = -1; $results = $this->FooBar->find('all', array('fields' => array('id', 'name'), 'conditions' => array('name LIKE "%'.$_GET['term'].'%"'))); $response = array(); $i = 0; foreach($results as $result){ $response[$i]['value'] = $result['FooBar']['name']; $response[$i]['id'] = $result['FooBar']['id']; $i++; } echo json_encode($response); } } ?>
source share