Using CAutoComplete to display one value and submit another

Note: CAutoComplete is deprecated since Yii 1.1.3. Consider using CJuiAutoComplete.

Have you ever wanted to use an auto-complete field to look up a user or some other data, but want the database ID of that user or data returned as well so that you can more easily perform some function when the form is submitted? Thanks to Yii's CAutoComplete widget and jQuery's Autocomplete plugin, it's really quite simple.

In overview, assuming that you are looking up and retrieving your data set for the autocomplete widget from a database, there are basically three steps:

  1. write action code to query and produce a properly-formatted list of autocomplete items
  2. embed the CAutoComplete widget into your view file and configure it to reference a controller's action
  3. chain an extra "result" method onto the end of the autocomplete widget to tell it to put your ID value into a hidden field when an autocomplete item is selected.

While not all features and options are explored, here is a sample of how to implement the above steps.

In your controller, create a new action to handle autocomplete lookup queries, like so:

<?php
    //Action
    public function actionAutoCompleteLookup()
    {
       if(Yii::app()->request->isAjaxRequest && isset($_GET['q']))
       {
			/* q is the default GET variable name that is used by
			/ the autocomplete widget to pass in user input
			*/
          $name = $_GET['q']; 
					// this was set with the "max" attribute of the CAutoComplete widget
          $limit = min($_GET['limit'], 50); 
          $criteria = new CDbCriteria;
          $criteria->condition = "name LIKE :sterm";
          $criteria->params = array(":sterm"=>"%$name%");
          $criteria->limit = $limit;
          $userArray = User::model()->findAll($criteria);
          $returnVal = '';
          foreach($userArray as $userAccount)
          {
             $returnVal .= $userAccount->getAttribute('name').'|'
						                 .$userAccount->getAttribute('user_id')."\n";
          }
          echo $returnVal;
       }
    }

There are a few things to notice here:

  1. A pipe "|" delimiter is used and natively recognized by jQuery to split a returned item into parts
  2. Each autocomplete item is terminated by a newline character, or "\n"; note that the newline char must be enclosed in double quotes (") not single quotes(')
  3. The resulting items are "returned" to the javascript autocomplete code through an `echo` statement; using `return` will not work

Now, in your view file, embed the following code within your form:

<?php $this->widget('CAutoComplete',
          array(
						 //name of the html field that will be generated
             'name'=>'user_name', 
						 //replace controller/action with real ids
             'url'=>array('controller/action'), 
             'max'=>10, //specifies the max number of items to display
						 
						 //specifies the number of chars that must be entered 
						 //before autocomplete initiates a lookup
             'minChars'=>2, 
             'delay'=>500, //number of milliseconds before lookup occurs
             'matchCase'=>false, //match case when performing a lookup?
						 
						 //any additional html attributes that go inside of 
						 //the input field can be defined here
             'htmlOptions'=>array('size'=>'40'), 

             'methodChain'=>".result(function(event,item){\$(\"#user_id\").val(item[1]);})",
             ));
    ?>
    <?php echo CHtml::hiddenField('user_id'); ?>

Take note of the methodChain attribute being used. MethodChain essentially appends (or chains) a javascript method to the end of the AutoComplete javascript code that will be generated. This particular method is the result method, which fires when an autocomplete item is selected. The code inside of the result function basically references the hidden field that was defined and assigns the 2nd part (part after the pipe) of the selected autocomplete data to that field.

Now that the basics are out of the way, review the documentation for Yii's CAutoComplete widget and jQuery's Autocomplete plugin to find more ways to customize and use autocomplete functionality in your Yii project.

7 3
11 followers
Viewed: 54 228 times
Version: 1.1
Category: Tutorials
Written by: luoshiben
Last updated by: mohammad sharif ahrari
Created on: Mar 25, 2009
Last updated: 5 years ago
Update Article

Revisions

View all history

Related Articles