1. You'll need to include the Ajax and Javascript helpers in your controller:
class PostsController extends AppController {
var $name = 'Posts';
var $helpers = array('Html','Ajax','Javascript');
var $components = array( 'RequestHandler' );
}
2. Once you have the javascript in your controller, you can use javascript helper link() method to include Prototype and Scriptaculous in view/layout/default.ctp
echo $html->script('prototype');
echo $html->script('scriptaculous');
Download Prototype
- save it in /webroot/js/prototype.js
Download Scriptaculous
- save all it in /webroot/js/
3. You need to set up a controller action that fetches and organizes the data you'll need for your list, based on user input:
#/app/controllers/posts_controller.php
function autoComplete() {
//Partial strings will come from the autocomplete field as
//$this->data['Post']['title']
$this->set('posts', $this->Post->find('all', array(
'conditions' => array(
'Post.title LIKE' => $this->data['Post']['title'].'%'
),
'fields' => array('title')
)));
$this->layout = 'ajax';
}
4. Create
app/views/posts/auto_complete.ctp
that uses that data and creates an unordered list:<ul>
<?php foreach($posts as $post): ?>
<li><?php echo $post['Post']['title']; ?></li>
<?php endforeach; ?>
</ul>
5. Finally, utilize autoComplete() in a view to create your auto-completing form field:
<?php echo $this->Form->create('Post', array('url' => '/posts/index')); ?>
<fieldset>
<legend><?php __('Search Post'); ?></legend>
<?php echo $ajax->autoComplete('Post.title', '/posts/autoComplete')?>
</fieldset>
<?php echo $this->Form->end(__('Find!!!', true));?>
Once you've got the autoComplete() call working correctly, use CSS to style the auto-complete suggestion box. You might end up using something similar to the following:
div.auto_complete {
position :absolute;
width :250px;
background-color :white;
border :1px solid #888;
margin :0px;
padding :0px;
}
li.selected { background-color: #ffb; }