Welcome to the Cookbook

loading...

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';
}
  1. function autoComplete() {
  2. //Partial strings will come from the autocomplete field as
  3. //$this->data['Post']['subject']
  4. $this->set('posts', $this->Post->find('all', array(
  5. 'conditions' => array(
  6. 'Post.subject LIKE' => $this->data['Post']['subject'].'%'
  7. ),
  8. 'fields' => array('subject')
  9. )));
  10. $this->layout = 'ajax';
  11. }

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> 
  1. <ul>
  2. <?php foreach($posts as $post): ?>
  3. <li><?php echo $post['Post']['subject']; ?></li>
  4. <?php endforeach; ?>
  5. </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')?>
  1. <?php echo $form->create('User', array('url' => '/users/index')); ?>
  2. <?php echo $ajax->autoComplete('Post.subject', '/posts/autoComplete')?>
  3. <?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));
  1. $ajax->autoComplete('Post.subject', '/posts/autoComplete',array('minChars' => 3));