7.1.2.8 autoComplete
autoComplete(string $field, string $url, array $options)
Renders a text field with $field with autocomplete. The remote action at $url should return a suitable list of autocomplete terms. Often an unordered list is used for this. First, you need to set up a controller action that fetches and organizes the data you'll need for your list, based on user input:
function autoComplete() {
//Partial strings will come from the autocomplete field as
//$this->data['Post']['subject']
$this->set('posts', $this->Post->find('all', array(
'conditions' => array(
'Post.subject LIKE' => $this->data['Post']['subject'].'%'
),
'fields' => array('subject')
)));
$this->layout = 'ajax';
} function autoComplete() {//Partial strings will come from the autocomplete field as//$this->data['Post']['subject']$this->set('posts', $this->Post->find('all', array('conditions' => array('Post.subject LIKE' => $this->data['Post']['subject'].'%'),'fields' => array('subject'))));$this->layout = 'ajax';}
Next, create app/views/posts/auto_complete.ctp that uses that data and creates an unordered list in (X)HTML:
<ul>
<?php foreach($posts as $post): ?>
<li><?php echo $post['Post']['subject']; ?></li>
<?php endforeach; ?>
</ul> <ul><?php foreach($posts as $post): ?><li><?php echo $post['Post']['subject']; ?></li><?php endforeach; ?></ul>
Finally, utilize autoComplete() in a view to create your auto-completing form field:
<?php echo $form->create('User', array('url' => '/users/index')); ?>
<?php echo $ajax->autoComplete('Post.subject', '/posts/autoComplete')?>
<?php echo $form->end('View Post')?>
<?php echo $form->create('User', array('url' => '/users/index')); ?><?php echo $ajax->autoComplete('Post.subject', '/posts/autoComplete')?><?php echo $form->end('View Post')?>
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; }
If you want the user to enter a minimum number of characters before the autocomplete starts, you can use the minChars-Option as follows:
$ajax->autoComplete('Post.subject', '/posts/autoComplete',array('minChars' => 3)); $ajax->autoComplete('Post.subject', '/posts/autoComplete',array('minChars' => 3));


























